Linux Shell Scripting Tutorial for DevOps

Linux Shell Scripting Tutorial

Introduction

Shell scripting is the oldest automation skill in DevOps, and still the one you will use most often. Before there were pipelines and GitOps, there were shell scripts: a backup that runs at 2 a.m., a deploy that pulls the latest code and restarts a service, a health check that pages someone when a disk fills up. Those scripts still run the world, and the engineers who can write them well are the ones other engineers ask for help.

This tutorial teaches Bash scripting the way it is actually used in operations: strict mode so failures stop the script instead of silently continuing, variables and quoting done correctly, loops and conditionals, functions, and error handling — ending with two complete scripts you can run, a backup script and a deploy script. You need the terminal basics from our Linux Commands guide. If a script starts needing data structures or API calls, that is the point to switch to Python — our Python for DevOps tutorial covers that side.

Version note (28 Nov 2026): the current Bash is 5.3, released 30 July 2025. The scripts here use only long-stable features, so they run on Bash 4.4 and newer as well — but check your version with bash –version before assuming a feature exists.

Tested 28 Nov 2026 on Bash 5.2.21: hello.sh, the quoting, loop and function examples all ran as written, strict mode caught an unbound variable, and the backup script produced a working tarball. The deploy script and ssh loop were not run — they need a real application and servers.

Your First Script — and Strict Mode

A Bash script is a text file with a shebang on the first line telling the kernel which interpreter to run it with:

#!/bin/bash
echo "Hello from Bash"

Save it as hello.sh, make it executable with chmod +x hello.sh, and run it with ./hello.sh. That is the whole mechanism — everything else in this tutorial is discipline around it.

The first discipline is strict mode. Put these two lines at the top of every script you write:

#!/bin/bash
set -euo pipefail

Each flag fixes a way Bash silently does the wrong thing by default:

  • set -e (errexit): exit immediately if a command fails. Without it, a script keeps running after a failed step — deploying the code that failed to download, or backing up the directory that failed to mount.
  • set -u (nounset): referencing an unset variable is an error. Without it, a typo like $SRV instead of $SERVER silently expands to an empty string, and your script deletes or deploys to nowhere.
  • set -o pipefail: a pipeline’s exit status is that of the rightmost command that failed, not just the last one. Without it, mysqldump mydb | gzip > backup.sql.gz reports success even if mysqldump failed — and you discover the backup is empty when you need it most.

Strict mode has one exception to remember: commands in tested contexts — if conditions, while loops, || and && chains — do not trigger set -e. That is a feature, not a bug: if grep -q “error” log.txt; then … is supposed to be allowed to fail.

Variables and Quoting — Where Scripts Break

Variables in Bash are untyped strings, and quoting is where most scripts break. The rules are short:

APP_NAME="myapp"          # no spaces around =
DEPLOY_DIR="/opt/$APP_NAME"
echo "Deploying $APP_NAME to $DEPLOY_DIR"
echo 'Single quotes do not expand $APP_NAME'

Double quotes allow expansion; single quotes do not. The rule that saves the most debugging time is this: always double-quote your variables. An unquoted $FILE with a space in it becomes two arguments, and a command that worked for a year breaks the day a filename contains a space:

# Wrong — breaks on spaces
rm $BACKUP_FILE
# Right
rm "$BACKUP_FILE"

Use ${VAR} with braces when the variable touches other text (“${APP_NAME}-v2”), and ${VAR:-default} to supply a fallback when a variable may be unset — useful for optional configuration. Command substitution captures a command’s output into a variable:

DATE=$(date +%Y-%m-%d)
BACKUP_FILE="backup-$DATE.tar.gz"

Bash 5.3 added a new form, ${ command; }, that runs a command in the current shell instead of a subshell — a niche feature you can ignore until you need it, but a useful sign that the shell is still evolving.

Conditionals, Loops and Tests

Conditionals use if with test expressions. The modern form is [[ ]], which is safer than the older [ ] — it does not do word splitting or pathname expansion on its arguments:

if [[ -f "$CONFIG_FILE" ]]; then
  echo "Config found: $CONFIG_FILE"
elif [[ -d "$CONFIG_DIR" ]]; then
  echo "Config directory found"
else
  echo "No config found" >&2
  exit 1
fi

Common tests: -f (is a regular file), -d (is a directory), -z (string is empty), -n (string is not empty), == for string equality, -eq / -lt / -gt for numbers. Note >&2 — it sends the error message to standard error instead of standard output, so errors and normal output can be separated. Every error message in a script should go to stderr.

Loops are how a script does the same thing to many things:

for server in web1 web2 web3; do
  echo "Checking $server..."
  ssh "$server" uptime || echo "$server is unreachable" >&2
done

count=0
while [[ $count -lt 3 ]]; do
  echo "Attempt $((count + 1))"
  count=$((count + 1))
done

$(( )) is arithmetic expansion — the safe way to do maths in Bash. And || after a command means “if this failed, do that instead”, which is the idiomatic way to handle an expected failure without tripping set -e.

Functions — Make Scripts Readable

A script longer than about fifty lines needs functions. A function groups a job under a name, takes arguments as $1, $2 and so on, and returns a status code:

log() {
  echo "[$(date +%H:%M:%S)] $*"
}

deploy_app() {
  local app_name="$1"
  local version="$2"
  log "Deploying $app_name version $version"
  # deployment steps here
  return 0
}

deploy_app "myapp" "1.4.2"

Two conventions matter. First, local confines a variable to the function — without it, every variable is global, and a function can silently overwrite a variable the rest of the script depends on. Second, a function “returns” a status code (0 for success), not a value: if you need a value out of a function, print it and capture it with command substitution.

A Complete Backup Script

Here is a backup script that uses everything so far — strict mode, variables, functions, conditionals and error handling — and is safe to run:

#!/bin/bash
set -euo pipefail

SOURCE_DIR="${1:-/var/www/html}"
BACKUP_DIR="${2:-/backups}"
DATE=$(date +%Y-%m-%d)
BACKUP_FILE="$BACKUP_DIR/backup-$DATE.tar.gz"

log() {
  echo "[$(date +%H:%M:%S)] $*"
}

if [[ ! -d "$SOURCE_DIR" ]]; then
  echo "Error: source directory $SOURCE_DIR does not exist" >&2
  exit 1
fi

mkdir -p "$BACKUP_DIR"
log "Backing up $SOURCE_DIR to $BACKUP_FILE"
tar -czf "$BACKUP_FILE" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"

if [[ ! -s "$BACKUP_FILE" ]]; then
  echo "Error: backup file is empty" >&2
  exit 1
fi

log "Backup complete: $BACKUP_FILE ($(du -h "$BACKUP_FILE" | cut -f1))"
find "$BACKUP_DIR" -name "backup-*.tar.gz" -mtime +30 -delete
log "Backups older than 30 days removed"

The script takes the source and destination as optional arguments with sensible defaults, refuses to run if the source does not exist, verifies the backup is not empty before declaring success, and deletes backups older than 30 days. That last line is the difference between a backup script and a disk-full incident in six months. Run it from cron at 2 a.m. and it needs no further attention — until the day you need the backup, when the -s check and the rotation policy are what make it trustworthy.

A Complete Deploy Script

A deploy script has a different shape: it must be safe to run twice, and it must stop at the first failure. Strict mode gives you the second property; the first comes from writing each step to be idempotent:

#!/bin/bash
set -euo pipefail

APP_DIR="/opt/myapp"
REPO_URL="https://github.com/example/myapp.git"
SERVICE="myapp"

log() {
  echo "[$(date +%H:%M:%S)] $*"
}

if [[ -d "$APP_DIR/.git" ]]; then
  log "Updating existing checkout"
  git -C "$APP_DIR" pull --ff-only
else
  log "Cloning repository"
  git clone "$REPO_URL" "$APP_DIR"
fi

log "Installing dependencies"
npm --prefix "$APP_DIR" ci

log "Running tests"
npm --prefix "$APP_DIR" test

log "Restarting service"
sudo systemctl restart "$SERVICE"

log "Verifying service is up"
systemctl is-active --quiet "$SERVICE"
log "Deploy complete"

Note the order: pull the code, install dependencies, run the tests, and only then restart the service. A deploy that restarts before testing is a deploy that takes down a working service to install a broken one. –ff-only refuses to merge if the local checkout has diverged — a quiet guard against deploying from a dirty working copy. And systemctl is-active –quiet at the end turns “the restart command ran” into “the service is actually running”, which is the only claim worth making.

Linting and Debugging

Never debug a shell script by staring at it. Two tools do the work. ShellCheck (shellcheck.net) is a static analyser for shell scripts — paste a script into the website or install it and run shellcheck script.sh. It catches unquoted variables, useless cat calls, and the dozen other mistakes every shell programmer makes, each with a code (like SC2086) and an explanation. Run it on every script before you commit it; it is the single highest-value habit in this tutorial.

For runtime debugging, bash -x script.sh prints each command before running it, and set -x inside a script turns tracing on for one section. When a script fails in CI but works on your laptop, the difference is almost always the environment — an unset variable, a missing directory, a different working directory — and -x output shows you which one in seconds.

FAQ

Is Bash still worth learning in 2026?

Yes. Every Linux server, container image and CI runner has Bash. Python is better for complex logic — our Python for DevOps tutorial covers that — but for gluing commands together, nothing beats a shell script.

What is the difference between sh and bash?

sh is the POSIX shell standard; Bash is a superset of it. A script with a #!/bin/bash shebang can use Bash features like [[ ]] and arrays. A script with #!/bin/sh must stick to POSIX features. Use #!/bin/bash unless you have a reason not to.

Why does my script work when I run it but fail in cron?

Cron runs with a minimal environment: a different PATH, no interactive shell setup, and a different working directory. Use absolute paths, set PATH at the top of the script, and log output to a file so you can see the error.

Should I use set -euo pipefail in every script?

Yes, in every script you write for real use. The three flags convert silent failures into loud ones.

How do I pass secrets to a script safely?

Through environment variables or a secrets manager, never as arguments — command-line arguments are visible to every user on the system through the process list. And never commit a script containing a real password or key.

Conclusion

Shell scripting is not glamorous, and that is the point: a backup script that runs every night for a year without attention is worth more than a clever program that needs babysitting. The habits in this tutorial — strict mode, quoted variables, functions, checking that the thing you just did actually worked, and running ShellCheck before you commit — are the difference between a script and a liability.

From here, the path is practice: automate one real task a week, starting with the backup script above. When a script starts needing data structures or an API, that is the moment to reach for Python — and our DevOps Engineer Roadmap 2026 shows where both languages sit in the skill set employers actually hire for.

Sources checked 28 Nov 2026: GNU Bash (Bash 5.3, released 30 Jul 2025; new ${ command; } command substitution); GNU Bash Reference Manual (set -e/-u/-o pipefail definitions); ShellCheck (shellcheck.net — standard shell linter; version 0.11.0 per secondary source). Scripts are original and use only long-stable Bash features. External references: GNU Bash Reference Manual · ShellCheck.

—

Scroll to Top