# Customize or write simple scripts

> Write Bash scripts with the right shebang, tests, loops, read, seq and command substitution, check exit codes, mail root when something fails, and install scripts safely.

Source: https://aminbytes.dev/bytes/shells-and-scripting/shell-scripts/


A shell script is just the commands you already type, saved in a file. Once a task has more than two steps, or you need it every night at 3 a.m., a script does it the same way every time. Administrators write small scripts constantly: check the disks, rotate a backup, add a batch of users, warn root when something is wrong.

This byte covers what the LPIC-1 exam expects: the shebang line, arguments and exit codes, tests, `if` and `case`, `for`, `while` and `until` loops, `read`, `seq`, command substitution, chaining with `&&` and `||`, `exec`, mailing root, and where to install a script with which owner and permissions.

## Your first script and the shebang

```bash {title="hello.sh"}
#!/bin/bash
# hello.sh: greet someone
echo "Hello, $1!"
echo "Script name: $0"
echo "Number of arguments: $#"
echo "All arguments: $@"
```

```bash
chmod +x hello.sh
./hello.sh Amin Linux
```

```console
Hello, Amin!
Script name: ./hello.sh
Number of arguments: 2
All arguments: Amin Linux
```

The first line, `#!/bin/bash`, is the **shebang** (from "hash" and "bang", the names of `#` and `!`). When you run the file, the kernel reads that line and starts the named interpreter with your script as its argument. It must be the very first line, with no space or blank line before it.

| Shebang | Use it when |
| --- | --- |
| `#!/bin/bash` | You use Bash features such as `[[ ]]`, arrays or `((i++))` |
| `#!/bin/sh` | The script is plain POSIX `sh` and should run on any system |
| `#!/usr/bin/env bash` | Find `bash` on the `PATH` (handy when it lives somewhere else, like on BSD or macOS) |
| `#!/usr/bin/python3` | The same mechanism works for any interpreter |

`/bin/sh` isn't the same everywhere. On Debian and Ubuntu it's **dash**, a small and fast POSIX shell. On RHEL and Fedora it's Bash running in POSIX mode. A script that says `#!/bin/sh` but uses Bash syntax works on Fedora and breaks on Ubuntu:

```console
./check.sh: 2: [[: not found
```

Three ways to run a script, and how they differ:

| Command | Needs `+x`? | Uses the shebang? | Runs in |
| --- | --- | --- | --- |
| `./script.sh` (or its full path) | Yes | Yes | a new child process |
| `bash script.sh` | No | No, you picked the interpreter | a new child process |
| `source script.sh` or `. script.sh` | No | No | your current shell |

Comments start with `#`. Special variables you'll use all the time: `$0` (script name), `$1` to `$9` and `${10}` (arguments), `$#` (how many), `"$@"` (all of them, each kept as a separate word), `$?` (exit status of the last command) and `$$` (the script's process ID). `shift` drops `$1` and moves the others down by one.

## Exit status: success or failure

Every command returns a number when it ends, its **exit status**. `0` means success. Anything from `1` to `255` means some kind of failure. `$?` holds the status of the last command:

```bash
ls /nope
echo $?
true;  echo $?
false; echo $?
nosuchcmd; echo $?
```

```console
ls: cannot access '/nope': No such file or directory
2
0
1
bash: nosuchcmd: command not found
127
```

Some values have a fixed meaning: `126` means "found but not executable", `127` means "command not found", and `128 + n` means the program was killed by signal `n` (130 is Ctrl+C).

Statuses can also carry information, not just pass or fail. `grep` returns `0` when it found a match, `1` when it didn't, and `2` on an error. That makes `grep -q` (quiet) perfect for decisions:

```bash
if grep -q '^amin:' /etc/passwd; then
    echo "user amin exists"
fi
```

Your own script ends with `exit n`. Without it, the script returns the status of its last command. Return `0` on success and a non-zero code for each kind of failure, so other scripts and cron can react.

## Chained commands

| Syntax | Runs the next command |
| --- | --- |
| `cmd1 ; cmd2` | always |
| `cmd1 && cmd2` | only if `cmd1` **succeeded** (status 0) |
| `cmd1 \|\| cmd2` | only if `cmd1` **failed** (non-zero) |
| `cmd1 \| cmd2` | at the same time, with `cmd1`'s output as `cmd2`'s input (a pipe) |

```bash
mkdir /tmp/x && cd /tmp/x && echo "ready"
cd /nope 2>/dev/null || echo "cd failed"
cd /srv/app || exit 1
```

The last line is a classic: if the `cd` fails, stop the script instead of running the rest in the wrong directory.

> [!WARNING]
> `a && b || c` is not a real if/else. `c` runs when `a` fails, but **also** when `a` works and `b` fails. Use `if` when that matters.

## Tests: `test`, `[ ]` and `[[ ]]`

`test` checks a condition and returns `0` (true) or `1` (false). `[ ... ]` is the same command with a different name, and it needs spaces inside the brackets:

```bash
test -d /etc && echo "dir"
[ 5 -gt 3 ] && echo "yes"
[ "abc" = "abd" ] || echo "different"
```

```console
dir
yes
different
```

The operators you need:

| Files | True if | Strings | True if | Numbers | True if |
| --- | --- | --- | --- | --- | --- |
| `-e f` | exists | `-z s` | empty | `a -eq b` | equal |
| `-f f` | regular file | `-n s` | not empty | `a -ne b` | not equal |
| `-d f` | directory | `s1 = s2` | equal | `a -lt b` | less than |
| `-L f` | symbolic link | `s1 != s2` | not equal | `a -le b` | less or equal |
| `-r` `-w` `-x f` | readable, writable, executable | | | `a -gt b` | greater than |
| `-s f` | exists and is not empty | | | `a -ge b` | greater or equal |
| `f1 -nt f2` | `f1` is newer than `f2` | | | | |

`!` negates a test: `[ ! -f /etc/nologin ]`. Combine tests with `&&` and `||` between brackets: `[ -f "$f" ] && [ -r "$f" ]`. The old `-a` (and) and `-o` (or) inside one `[ ]` still work but are discouraged.

Notice that numbers use letters (`-lt`) and strings use symbols (`=`). `[ 10 < 9 ]` doesn't compare at all: `<` is a redirection there. Always quote variables, `[ "$name" = "root" ]`, or an empty variable turns into a syntax error.

`[[ ... ]]` is the Bash version. It doesn't split words, so quoting is less critical, and it adds pattern matching (`[[ $f == *.log ]]`) and regular expressions (`[[ $ip =~ ^[0-9.]+$ ]]`). It doesn't exist in `sh` or dash.

## Decisions: `if` and `case`

`if` runs a command and checks its exit status. Usually that command is a test, but any command works:

```bash {title="checkfile.sh"}
#!/bin/bash
file="$1"

if [ -z "$file" ]; then
    echo "Usage: $0 FILE" >&2
    exit 2
elif [ -d "$file" ]; then
    echo "$file is a directory"
elif [ -f "$file" ]; then
    echo "$file is a regular file of $(wc -c < "$file") bytes"
else
    echo "$file does not exist"
    exit 1
fi
```

```bash
./checkfile.sh /etc
./checkfile.sh /etc/hostname
./checkfile.sh /nope; echo "exit=$?"
```

```console
/etc is a directory
/etc/hostname is a regular file of 13 bytes
/nope does not exist
exit=1
```

`>&2` sends the usage message to standard error, where error messages belong. `if` closes with `fi`, `case` with `esac`. `case` matches one value against patterns, which is cleaner than a long `elif` chain:

```bash
case "$answer" in
    y|Y|yes) echo "Deleting..." ;;
    n|N|no)  echo "Keeping them." ;;
    *)       echo "Please answer y or n."; exit 1 ;;
esac
```

## Asking the user: `read`

`read` takes one line from standard input and stores it in variables:

```bash {title="ask.sh"}
#!/bin/bash
read -p "What's your name? " name
read -s -p "Password: " pass; echo
echo "Hello $name, your password has ${#pass} characters."
```

```console
What's your name? Amin
Password:
Hello Amin, your password has 9 characters.
```

| Option | Effect |
| --- | --- |
| `-p "text"` | show a prompt |
| `-s` | silent: don't echo what's typed |
| `-t 10` | give up after 10 seconds |
| `-n 1` | return after one character |
| `-r` | raw: keep backslashes as they are (use it almost always) |
| `-a arr` | read the words into an array |

With several variable names, `read` splits the line on spaces and the **last** variable gets the rest. With no name at all, the line lands in `$REPLY`:

```bash
read a b <<< "one two three"; echo "a=$a b=$b"
```

```console
a=one b=two three
```

## Loops: `for`, `while` and `until`

`for` walks through a list of words, file names or command output:

```bash
for f in /etc/host*; do
    echo "found $f"
done

for user in alice bob carol; do
    sudo useradd -m "$user"
done
```

```console
found /etc/host.conf
found /etc/hostname
found /etc/hosts
```

For a list of numbers, use `seq` or Bash's brace expansion `{1..5}`:

```bash
for i in $(seq 1 3); do echo "pass $i"; done
for ((i = 1; i <= 3; i++)); do echo "$i"; done    # C-style, Bash only
```

`seq` prints a sequence. With one number it counts from 1, with two it's first and last, with three it's first, step and last:

| Command | Output |
| --- | --- |
| `seq 3` | `1 2 3` (one per line) |
| `seq 2 2 8` | `2 4 6 8` |
| `seq 5 -1 1` | `5 4 3 2 1` |
| `seq -w 8 11` | `08 09 10 11` (equal width) |
| `seq -s, 1 5` | `1,2,3,4,5` (custom separator) |

`while` repeats as long as its command succeeds. `until` is the opposite: it repeats until the command succeeds. `$(( ))` does integer math:

```bash {title="count.sh"}
#!/bin/bash
count=3
while [ "$count" -gt 0 ]; do
    echo "$count..."
    count=$((count - 1))
done
echo "Liftoff!"

until ping -c1 -W1 192.168.1.1 >/dev/null; do
    sleep 5          # wait for the network
done
```

The most useful `while` is reading a file line by line. Here `IFS=:` splits each line of `/etc/passwd` on colons, and `_` catches fields you don't need:

```bash {title="users.sh"}
#!/bin/bash
while IFS=: read -r user _ uid _ _ _ shell; do
    if [ "$uid" -ge 1000 ] && [ "$uid" -lt 65534 ]; then
        echo "$user uses $shell"
    fi
done < /etc/passwd
```

```console
amin uses /bin/bash
carol uses /bin/sh
```

`break` leaves a loop early, `continue` skips to the next round.

## Command substitution

`$(command)` runs a command and puts its output right into the line. The older form uses backticks, `` `command` ``:

```bash
echo "Today is $(date +%A)"
kernel=`uname -r`
backup="/backup/etc-$(hostname)-$(date +%F).tar.gz"
tar czf "$backup" /etc
```

```console
Today is Tuesday
```

Prefer `$( )`: it's easier to read and nests without escaping, as in `$(dirname $(readlink -f "$0"))`. The trailing newline of the output is removed.

## `exec`: replace the shell

`exec command` replaces the current shell with `command`. There's no child process and no return: whatever comes after it in the script never runs.

```bash
bash -c 'echo before; exec echo replaced; echo never'
```

```console
before
replaced
```

Two common uses:

- **Wrapper scripts** that prepare the environment, then hand over: `exec /opt/app/bin/server "$@"`. The program keeps the script's process ID and gets signals directly.
- **Redirecting the rest of a script**: `exec` with only redirections changes where the current shell's output goes, from that line on.

```bash
#!/bin/bash
exec >> /var/log/nightly.log 2>&1
echo "started at $(date +%T)"     # goes to the log, not the screen
```

Typed in an interactive shell, `exec zsh` replaces your Bash with zsh, and `exec ls` runs `ls` and then closes your terminal.

## Mailing root when something goes wrong

Scripts that run unattended need a way to shout. The classic one is a mail to the local superuser with `mail`. `-s` sets the subject, and the body comes from standard input:

```bash {title="/usr/local/sbin/diskcheck.sh"}
#!/bin/bash
# Mail root when a filesystem is over the limit
LIMIT=90

df --output=pcent,target -x tmpfs -x devtmpfs | tail -n +2 |
while read -r pcent target; do
    used=${pcent%\%}                      # "93%" becomes "93"
    if [ "$used" -ge "$LIMIT" ]; then
        echo "$target is ${used}% full on $(hostname)" |
            mail -s "Disk warning: $target" root
    fi
done
```

The same idea in one line, mailing only when a backup **fails**:

```bash
rsync -a /home/ /backup/home/ || echo "rsync failed with status $?" | mail -s "Backup failed" root
```

`mail` comes from the `mailutils` or `bsd-mailx` package on Debian and Ubuntu, and from `s-nail` on RHEL 9 and Fedora. It needs a local mail server (an MTA such as Postfix) to deliver the message. Mail to `root` usually lands in `/var/mail/root` or is forwarded to a real person through `/etc/aliases`. (Side note: Cron does this for you too: anything a cron job prints is mailed to the job's owner, or to the address in `MAILTO`. That's why quiet scripts only print when something is wrong.)

## Location, ownership and permissions

**Where to put it:**

- `/usr/local/bin` for scripts every user may run, `/usr/local/sbin` for admin-only scripts. These folders are on the default `PATH` and package updates never touch them.
- `~/bin` or `~/.local/bin` for your personal scripts. On Debian and Ubuntu, `~/.profile` adds them to `PATH` when they exist (log in again after creating them).
- Not `/usr/bin` or `/bin`: those belong to the package manager.

**Who owns it, and who may run it:**

```bash
sudo install -o root -g root -m 755 diskcheck.sh /usr/local/sbin/diskcheck.sh
ls -l /usr/local/sbin/diskcheck.sh
```

```console
-rwxr-xr-x 1 root root 381 Dec  1 09:30 /usr/local/sbin/diskcheck.sh
```

`install` copies, sets the owner and sets the mode in one step. Doing it by hand is `cp`, `chown root:root` and `chmod 755` (or `chmod +x`, `chmod u+x`).

A script needs **read** and **execute** permission, because the interpreter has to read the file. A compiled program runs with only `x`, but a script with mode `711` fails for other users with `Permission denied` (exit status 126). A script that root runs, for example from cron, must be writable by root only: if another user can edit it, they can make root run anything.

**SUID:** `chmod u+s file` (or `chmod 4755`) sets the SUID bit, shown as `s` in `rwsr-xr-x`. On a compiled program like `passwd`, it runs with the file owner's rights. On a script, **Linux ignores SUID and SGID**. Try it with a tiny script that prints who it runs as:

```bash {title="/usr/local/bin/whoami.sh"}
#!/bin/bash
id -un
```

```bash
sudo chmod 4755 /usr/local/bin/whoami.sh
ls -l /usr/local/bin/whoami.sh
/usr/local/bin/whoami.sh       # run it as the normal user bob
```

```console
-rwsr-xr-x 1 root root 19 Dec  1 09:35 /usr/local/bin/whoami.sh
bob
```

The bit is set, yet the script still runs as `bob`. SUID scripts were a security hole (a user could swap the file between the kernel reading the shebang and the interpreter opening it), so the kernel refuses to honor them. When a user needs to run a script as root, give them a specific `sudo` rule instead. To audit SUID files on a system: `find / -perm -4000 -type f 2>/dev/null`.

> [!TIP]
> Check a script for syntax errors without running it: `bash -n script.sh`. Watch it run line by line: `bash -x script.sh`, or put `set -x` in the script. The free `shellcheck` tool catches quoting bugs and Bash-only syntax in `#!/bin/sh` scripts.

## Exam checklist

- The shebang `#!/bin/bash` (or `#!/bin/sh`, `#!/usr/bin/env bash`) must be the first line. `bash script.sh` ignores it and doesn't need `+x`. On Debian `/bin/sh` is dash.
- Exit status: `0` is success, non-zero is failure, `$?` holds the last one. `126` not executable, `127` not found. End scripts with `exit n`.
- `;` always, `&&` on success, `||` on failure. `cmd || exit 1` stops a script on errors.
- `test` and `[ ]` are the same: `-f -d -e -r -w -x -s -z -n`, `=` and `!=` for strings, `-eq -ne -lt -le -gt -ge` for numbers. Spaces inside the brackets, quotes around variables.
- `if ...; then ...; elif ...; else ...; fi` and `case ... in pattern) ... ;; esac`.
- `for x in list; do ...; done`, `while cmd; do ...; done`, `until cmd; do ...; done`. `while read -r line; do ...; done < file` reads a file line by line.
- `read -p` prompts, `-s` hides input; the last variable gets the rest of the line; no variable means `$REPLY`.
- `seq LAST`, `seq FIRST LAST`, `seq FIRST STEP LAST`, plus `-w` and `-s`.
- `$(cmd)` and `` `cmd` `` are command substitution. `exec cmd` replaces the shell; `exec > file` redirects the rest of the script.
- Mail root with `echo "msg" | mail -s "subject" root`. Install scripts in `/usr/local/bin` or `/usr/local/sbin`, owned by root, mode `755`. SUID is ignored on scripts.


## Byte check

1. What does `mkdir /backup && cp -a /etc /backup/ || echo "failed"` do when `mkdir` fails?
   - It runs `cp` anyway, then prints `failed`
   - **It skips `cp` and prints `failed`** (correct)
   - It stops without running anything else
   `&&` runs the next command only if the previous one succeeded (exit status 0). `||` runs only after a failure, so `mkdir` failing skips `cp` and triggers the `echo`.

2. You run `chmod u+s /usr/local/bin/report.sh` on a root-owned Bash script. A normal user runs it. As which user does it run?
   - As root, because of the SUID bit
   - **As the user who started it: Linux ignores SUID on scripts** (correct)
   - It refuses to start
   The Linux kernel ignores the SUID and SGID bits on interpreted scripts for security reasons. Use `sudo` with a specific rule instead.

3. Which line makes a script always run with Bash, even when you start it as `./script` from another shell?
   - `# bash` on the first line
   - **`#!/bin/bash` on the first line** (correct)
   - `exec bash` on the last line
   The shebang (`#!`) must be the very first line. The kernel reads it and starts that interpreter with the script as its argument.


