# Shell scripting: automate it once, run it forever

Bash scripts that are safe in production: variables and quoting, if and case, loops, functions and exit codes, strict mode, debugging, and running on a schedule.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 14. About 45 minutes, intermediate. Source: https://devops.rajeev.pro/courses/linux/14-shell-scripting

## What you will learn

- Write a script with a shebang, run it, and pass it arguments
- Use variables, defaults and quoting without the classic word-splitting bugs
- Branch with if, [[ ]] and case, and loop over files, lines and numbers
- Write functions, return exit codes, and stop on errors with set -euo pipefail
- Debug a script with bash -x and check it with ShellCheck
- Schedule a script with cron or a systemd timer

## Your first script

**The problem.** Every Friday you deploy by hand: SSH in, pull the code, install dependencies, run
the migrations, restart the service, check it came back. It's six commands and it takes five
minutes. One Friday you're tired and run them out of order, or on the wrong server, and production
is down for an hour. Another week you're on holiday, and nobody else remembers the exact steps.

**What a script changes.** A script is the commands you'd type, saved in a file. It runs them in
the same order every time, it can check that each step worked before moving on, and anyone on the
team can read or run it. If you've run the same five commands twice, they belong in a script. In
this lesson you'll build up from "hello" to scripts that are safe to run unattended.

```sh
#!/usr/bin/env bash
# hello.sh: say hello to a name, or to the user running it
name=${1:-$USER}
echo "Hello, $name. Today is $(date +%A)."
```

```sh
$ chmod +x hello.sh               # make it executable (once)
$ ./hello.sh                      # ./ because the current folder isn't in $PATH
Hello, rajeev. Today is Tuesday.
$ ./hello.sh team
Hello, team. Today is Tuesday.
```

The first line, the **shebang**, says which program runs the file. `#!/usr/bin/env bash` finds
bash wherever it's installed. Use bash, not `sh`, when you use bash features such as `[[ ]]` and
arrays: on Ubuntu `sh` is `dash`, which doesn't have them.

> **Figure.** The anatomy of a production script. The shebang line. set -euo pipefail, strict mode. Arguments with defaults and a usage message. Small functions such as log and die. Checks before doing anything. The work itself. Exit codes: 0 for success, non-zero for failure, which cron, systemd and CI read. On the right, what each part protects against.
>
> The same shape works for almost every ops script: strict mode, inputs, checks, work, a clear exit code.

> **Video.** [How To Write Bash Scripts In Linux - Complete Guide (Part 2 - Hello World)](https://www.youtube.com/watch?v=boqC9QenshY&t=303s) (Learn Linux TV)

## Variables, arguments and quoting

A script that only works for one app or one server isn't much use. Variables let you write it once
and change the details: the app name, the folder, the date in a backup's file name. Arguments let
the person running it pass those details in, as in `./backup.sh /srv/app 7`.

```sh
$ app=myapp                       # no spaces around =
$ echo "$app is in /srv/$app"
myapp is in /srv/myapp
$ release=$(date +%Y%m%d)         # the output of a command
$ count=$((3 + 4))                # arithmetic
$ echo "${app}_v2"                # braces where the name would run on
myapp_v2
```

| In a script      | Means                           |
| ---------------- | ------------------------------- |
| `$1`, `$2` …     | arguments                       |
| `$#`             | how many arguments              |
| `"$@"`           | all arguments, each kept whole  |
| `$?`             | exit code of the last command   |
| `$$`             | this script's PID               |
| `${1:-7}`        | `$1`, or `7` if it's empty      |
| `${1:?usage: …}` | `$1`, or stop with that message |

**Quote every variable**: `"$file"`, not `$file`. Without quotes, bash splits the value on spaces and
expands `*`:

```sh
$ x="a b"
$ [ $x = "a b" ]
bash: [: too many arguments
$ [ "$x" = "a b" ] && echo match
match
```

Single quotes keep everything literal (`'$HOME'` prints `$HOME`); double quotes still expand
variables and `$( )`.

Quote expansions by default. `"$@"` preserves each argument as its own value, even when it contains spaces;
unquoted `$@` or `$file` can split and expand wildcard characters. Use `${name:-default}` to supply a default
and `${name:?message}` to stop when a required value is missing. A common mistake is writing spaces around
the assignment operator; `app = value` runs a command named `app` instead of assigning a variable.

> **Video.** [How To Write Bash Scripts In Linux - Complete Guide (Part 3 - Variables)](https://www.youtube.com/watch?v=uQE_4Q-HZZw&t=52s) (Learn Linux TV)

## Conditionals: if, test and case

Scripts need to choose a path based on whether a file exists, a command succeeded or an input matches an
expected value. Bash conditionals run a command and branch on its exit code: zero means success; non-zero
means failure. `[[ … ]]` is Bash's test expression and supports file, string, numeric and pattern checks.

```sh
if [[ -f /etc/myapp.env ]]; then
  echo "config found"
elif [[ -d /etc/myapp ]]; then
  echo "folder but no config"
else
  echo "not installed" >&2
  exit 1
fi

if grep -q "^deploy:" /etc/passwd; then echo "deploy user exists"; fi
[[ $(id -u) -eq 0 ]] || { echo "run as root" >&2; exit 1; }
```

| Test                                     | True when                        |
| ---------------------------------------- | -------------------------------- |
| `-f file` / `-d dir` / `-e path`         | it's a file / a folder / exists  |
| `-r` `-w` `-x file`                      | readable / writable / executable |
| `-z "$s"` / `-n "$s"`                    | string is empty / not empty      |
| `"$a" == "$b"` / `!=`                    | strings equal / differ           |
| `$n -eq 5` `-ne` `-lt` `-le` `-gt` `-ge` | number comparisons               |
| `"$s" =~ ^v[0-9]+`                       | matches a regular expression     |

`case` is the clean way to handle a fixed set of words, such as subcommands:

```sh
case "$1" in
  start|up) systemctl start myapp ;;
  stop)     systemctl stop myapp ;;
  *)        echo "usage: $0 start|stop" >&2; exit 2 ;;
esac
```

> **Video.** [How To Write Bash Scripts In Linux - Complete Guide (Part 5 - If Statements)](https://www.youtube.com/watch?v=YrE1Qg-Aw0Q&t=73s) (Learn Linux TV)

Use `if` for a success/failure check and `case` for a fixed set of command options. Quote variables inside
tests so empty values and spaces remain one argument. Send error messages to stderr and exit non-zero when
the script cannot continue. A common mistake is comparing numbers with string operators or treating an
unquoted empty variable as a valid test.

## Loops

Loops are where scripts start saving real time: the same check on 20 servers, the same cleanup on
every log file, the same request retried until a service comes up. Bash has three kinds: `for` goes
through a list, `while` repeats as long as a command succeeds, and `until` repeats until one does.

```sh
for f in /etc/*.conf; do                  # over files: a glob, never $(ls)
  echo "$f: $(wc -l < "$f") lines"
done

for host in web1 web2 web3; do            # over a list
  ssh "$host" uptime
done

for i in {1..5}; do echo "try $i"; done   # over numbers

while read -r user shell; do              # over lines of a file or command
  echo "$user uses $shell"
done < <(awk -F: '$7 ~ /bash/ {print $1, $7}' /etc/passwd)

until curl -fs http://localhost:8080/health > /dev/null; do   # retry until it works
  sleep 2
done
```

`read -r` keeps backslashes as they are; always use it. `break` leaves a loop and `continue` skips to
the next round.

Use a `while read` loop with a redirected file or process substitution when you need structured input. Add
timeouts or retry limits around loops that wait for a service, or they may run forever. A common mistake is
using `for line in $(cat file)`, which splits on whitespace and loses the original line boundaries.

> **Video.** [How To Write Bash Scripts In Linux - Complete Guide (Part 7 - While Loops)](https://www.youtube.com/watch?v=R0tTsdQ_9Vw&t=50s) (Learn Linux TV)

## Functions and exit codes

Functions group repeated work under a name and let you pass local inputs. Exit codes communicate the result
to the caller: `0` means success, while a non-zero value signals failure. Cron, systemd and CI use that
status to decide whether a job succeeded.

```sh
log() { echo "$(date +%T) $*" >&2; }      # messages go to stderr, data to stdout
die() { log "ERROR: $*"; exit 1; }

is_up() {
  local url=$1                            # local: doesn't leak out of the function
  curl -fs -m 5 "$url" > /dev/null        # the function returns curl's exit code
}

if is_up http://localhost:8080/health; then log "healthy"; else die "app is down"; fi
```

Every command, function and script ends with an **exit code**: `0` for success, `1`–`255` for
failure. That number is what `if`, `&&`, `||`, cron, systemd and CI pipelines read. A script that
fails but exits `0` lies to all of them, so end with `exit 1` (or `die`) when something went wrong.

### Strict mode

Put this on the second line of every script:

```sh
set -euo pipefail
```

| Flag          | Without it                                                                    |
| ------------- | ----------------------------------------------------------------------------- |
| `-e`          | a failed command is ignored and the script continues                          |
| `-u`          | a typo such as `$BACKUP_DRI` silently becomes empty: `rm -rf "$BACKUP_DRI"/*` |
| `-o pipefail` | `false \| true` counts as success, hiding the failure on the left             |

When a failure is expected, say so: `grep -q x file || true`, or test it in an `if`. One `-e` trap:
`((count++))` returns failure when `count` is 0, so write `count=$((count + 1))`.

Write log messages to stderr and reserve stdout for data another command may consume. Return the failing
command's status or call a helper such as `die` rather than printing an error and exiting successfully. A
common mistake is assuming `set -e` handles every failure; commands in conditions and pipelines have special
rules, so use explicit checks and `pipefail`.

> **Video.** [How To Write Bash Scripts In Linux - Complete Guide (Part 12 - Functions)](https://www.youtube.com/watch?v=6inWQZLF50I&t=43s) (Learn Linux TV)

## Debugging a script

A script can fail because of syntax, input or environment, and a long run may not show which command caused
it. Start with a syntax check that executes nothing, then use Bash tracing to see each expanded command. Run
the smallest relevant test case and remove secrets from trace output before sharing logs.

```sh
$ bash -n deploy.sh               # syntax check only, runs nothing
$ bash -x deploy.sh               # print every command as it runs
+ n=3
+ echo 'n is 3'
n is 3
```

Each `+` line is a command after its variables were filled in, so you see exactly what ran. Turn it
on for one section with `set -x` … `set +x`. Before you ship a script, run **ShellCheck**
(`sudo apt install shellcheck`, then `shellcheck deploy.sh`): it catches missing quotes and most of
the bugs in this lesson.

Use `bash -n` for a fast parse check and `bash -x` for a local diagnosis. Tracing can print expanded secret
values, so do not enable it around credentials or capture it in a public log. A common mistake is treating a
successful syntax check as proof that the script behaves correctly; test its success and failure paths too.

## Running scripts on a schedule

Automation runs without a person watching the terminal. The scheduler supplies a different environment and
working directory than your interactive shell, so scripts should use absolute paths, validate inputs and
write useful logs. **cron** runs commands at set times. Edit your table with `crontab -e`:

```text
# minute hour day-of-month month day-of-week  command
30 2 * * *     /opt/scripts/backup.sh /srv/app 7 >> /var/log/backup.log 2>&1
*/5 * * * *    /opt/scripts/health.sh
0 9 * * 1      /opt/scripts/weekly-report.sh
```

That's 02:30 every day, every 5 minutes, and 09:00 on Mondays. Cron runs with a tiny `$PATH` and no
terminal, so use full paths and send the output to a log, or it's lost. On systemd machines a
**timer** (from the _Services with systemd_ lesson) does the same job with logs in `journalctl` and a
record of failures.

Use cron for simple schedules, and a systemd timer when you need service dependencies and journal records.
Test the command as the same account that will run it and account for overlapping executions. A common
mistake is using a relative path that works in your terminal but points somewhere else from cron.

> **In production.** A script that runs unattended must be safe to run twice and to fail halfway. Use strict mode, check inputs before changing anything, write to a temporary file and `mv` it into place, and exit non-zero on failure so your monitoring sees it. Keep scripts in Git, not only on the server.

## Mission: A backup script you can trust

Write backup.sh: it takes a folder and how many backups to keep, makes a dated .tar.gz in ~/backups, deletes the oldest ones beyond that number, refuses bad input with a clear message, and exits non-zero on any failure.

- You need: Any folder, such as a small site-<date>.tar.gz"
>

```sh
#!/usr/bin/env bash
set -euo pipefail

src=${1:?usage: backup.sh <folder> [keep]}
keep=${2:-7}
dest="$HOME/backups"
stamp=$(date +%Y%m%d-%H%M%S)

log() { echo "$(date +%T) $*" >&2; }
die() { log "ERROR: $*"; exit 1; }

[[ -d $src ]] || die "$src is not a folder"
mkdir -p "$dest"

name=$(basename "$src")
archive="$dest/$name-$stamp.tar.gz"
tar -czf "$archive" -C "$(dirname "$src")" "$name"
log "created $archive ($(du -h "$archive" | cut -f1))"

count=0
for old in $(ls -1t "$dest/$name"-*.tar.gz | tail -n +$((keep + 1))); do
  rm -- "$old"
  count=$((count + 1))
done
log "removed $count old backup(s), keeping $keep"
```

```sh
$ chmod +x backup.sh
$ ./backup.sh site 2              # run it three times
05:35:09 created /home/rajeev/backups/site-20261013-053509.tar.gz (4.0K)
05:35:09 removed 1 old backup(s), keeping 2
$ ls ~/backups | wc -l
2
$ ./backup.sh nope; echo "exit $?"
05:35:09 ERROR: nope is not a folder
exit 1
```

Archive names have no spaces, so the `$(ls …)` loop is safe here; for arbitrary file names use
`find … -print0` with `while read -r -d ''`. To run it nightly: `crontab -e` and add
`30 2 * * * /home/rajeev/backup.sh /srv/site 7 >> /home/rajeev/backup.log 2>&1`.

## Try it

- Write a three-line script with `#!/usr/bin/env bash`, make it executable with `chmod +x`, and run it with `./`.
- Run `x="a b"; [ $x = "a b" ]` and read the error, then run it again with `"$x"`.
- Print `$?` after `true`, after `false`, and after `grep -q root /etc/passwd`.
- Loop over every `.conf` file in `/etc` and print its name and line count.
- Run any script with `bash -x` and read the `+` lines.
- Run `crontab -l`, then read the fields of a cron line in this lesson.

## Quiz

1. What does $? hold?
   - The number of arguments
   - **The exit code of the last command: 0 means success, anything else a failure** (answer)
   - The process ID of the script
   Why: Every command exits with a number. if, &&, || and set -e all decide by it. $# is the argument count and $$ the script's PID.

2. file="my report.txt"; rm $file. What happens?
   - my report.txt is deleted
   - **rm tries to delete two files, "my" and "report.txt"** (answer)
   - Nothing
   Why: Unquoted variables are split on spaces. Always write "$file". Many famous deletion bugs are exactly this.

3. What does set -euo pipefail give you?
   - Faster scripts
   - **Stop on the first failing command, treat unset variables as errors, and let a pipeline fail when any part fails** (answer)
   - Colour output
   Why: Without it, a script keeps going after a failure, for example deleting files after a backup that didn't happen. Exceptions are handled with if or || explicitly.

4. Which cron line runs a script at 02:30 every day?
   - 2 30 * * * /opt/backup.sh
   - **30 2 * * * /opt/backup.sh** (answer)
   - * * 2 30 * /opt/backup.sh
   Why: The fields are minute, hour, day of month, month, day of week. 30 2 means minute 30 of hour 2.

5. How do you see each command a script runs, with its variables filled in?
   - **bash -x script.sh (or set -x inside it)** (answer)
   - bash -n script.sh
   - echo every line
   Why: set -x prints each command after expansion, prefixed with +. bash -n only checks the syntax without running anything.

## Resources

- [bash(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/bash.1.html) (Ubuntu manpages)
- [ShellCheck: finds bugs in shell scripts](https://www.shellcheck.net/) (ShellCheck)
- [BashFAQ and pitfalls](https://mywiki.wooledge.org/BashPitfalls) (Greg's Wiki)
- [crontab(5): the cron table format](https://manpages.ubuntu.com/manpages/noble/man5/crontab.5.html) (Ubuntu manpages)
- [LPIC-1 objective 105.2: customise or write simple scripts](https://wiki.lpi.org/wiki/LPIC-1_Objectives_V5.0) (Linux Professional Institute)
