Menu
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.”
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#
#!/bin/bash
# hello.sh: greet someone
echo "Hello, $1!"
echo "Script name: $0"
echo "Number of arguments: $#"
echo "All arguments: $@"chmod +x hello.sh
./hello.sh Amin LinuxHello, 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:
./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:
ls /nope
echo $?
true; echo $?
false; echo $?
nosuchcmd; echo $?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:
if grep -q '^amin:' /etc/passwd; then
echo "user amin exists"
fiYour 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) |
mkdir /tmp/x && cd /tmp/x && echo "ready"
cd /nope 2>/dev/null || echo "cd failed"
cd /srv/app || exit 1The 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:
test -d /etc && echo "dir"
[ 5 -gt 3 ] && echo "yes"
[ "abc" = "abd" ] || echo "different"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:
#!/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./checkfile.sh /etc
./checkfile.sh /etc/hostname
./checkfile.sh /nope; echo "exit=$?"/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:
case "$answer" in
y|Y|yes) echo "Deleting..." ;;
n|N|no) echo "Keeping them." ;;
*) echo "Please answer y or n."; exit 1 ;;
esacAsking the user: read#
read takes one line from standard input and stores it in variables:
#!/bin/bash
read -p "What's your name? " name
read -s -p "Password: " pass; echo
echo "Hello $name, your password has ${#pass} characters."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:
read a b <<< "one two three"; echo "a=$a b=$b"a=one b=two three
Loops: for, while and until#
for walks through a list of words, file names or command output:
for f in /etc/host*; do
echo "found $f"
done
for user in alice bob carol; do
sudo useradd -m "$user"
donefound /etc/host.conf
found /etc/hostname
found /etc/hosts
For a list of numbers, use seq or Bash’s brace expansion {1..5}:
for i in $(seq 1 3); do echo "pass $i"; done
for ((i = 1; i <= 3; i++)); do echo "$i"; done # C-style, Bash onlyseq 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:
#!/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
doneThe 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:
#!/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/passwdamin 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`:
echo "Today is $(date +%A)"
kernel=`uname -r`
backup="/backup/etc-$(hostname)-$(date +%F).tar.gz"
tar czf "$backup" /etcToday 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 -c 'echo before; exec echo replaced; echo never'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:
execwith only redirections changes where the current shell’s output goes, from that line on.
#!/bin/bash
exec >> /var/log/nightly.log 2>&1
echo "started at $(date +%T)" # goes to the log, not the screenTyped 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:
#!/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
doneThe same idea in one line, mailing only when a backup fails:
rsync -a /home/ /backup/home/ || echo "rsync failed with status $?" | mail -s "Backup failed" rootmail 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.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/binfor scripts every user may run,/usr/local/sbinfor admin-only scripts. These folders are on the defaultPATHand package updates never touch them.~/binor~/.local/binfor your personal scripts. On Debian and Ubuntu,~/.profileadds them toPATHwhen they exist (log in again after creating them).- Not
/usr/binor/bin: those belong to the package manager.
Who owns it, and who may run it:
sudo install -o root -g root -m 755 diskcheck.sh /usr/local/sbin/diskcheck.sh
ls -l /usr/local/sbin/diskcheck.sh-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:
#!/bin/bash
id -unsudo 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-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.shignores it and doesn’t need+x. On Debian/bin/shis dash. - Exit status:
0is success, non-zero is failure,$?holds the last one.126not executable,127not found. End scripts withexit n. ;always,&&on success,||on failure.cmd || exit 1stops a script on errors.testand[ ]are the same:-f -d -e -r -w -x -s -z -n,=and!=for strings,-eq -ne -lt -le -gt -gefor numbers. Spaces inside the brackets, quotes around variables.if ...; then ...; elif ...; else ...; fiandcase ... in pattern) ... ;; esac.for x in list; do ...; done,while cmd; do ...; done,until cmd; do ...; done.while read -r line; do ...; done < filereads a file line by line.read -pprompts,-shides input; the last variable gets the rest of the line; no variable means$REPLY.seq LAST,seq FIRST LAST,seq FIRST STEP LAST, plus-wand-s.$(cmd)and`cmd`are command substitution.exec cmdreplaces the shell;exec > fileredirects the rest of the script.- Mail root with
echo "msg" | mail -s "subject" root. Install scripts in/usr/local/binor/usr/local/sbin, owned by root, mode755. SUID is ignored on scripts.
Answer these 3 questions to commit this byte to your learning path.
Reset. This byte isn't committed any more. Answer the questions again to commit it.
$ git commit -m "learn(lpic-105): Customize or write simple scripts"
[main 62f7b08] learn(lpic-105): Customize or write simple scripts
1 byte changed, 3 insertions(+)
See it on your path Already committed . Try the questions again any time, it won't undo anything. To uncommit it and start over: