Shell Scripting

Put commands in a script and let the computer do the repetitive work. Start with your first script, then variables, conditions, loops, functions and error handling.

01

Your first script

A shell script is simply commands written into a text file, in order, for the shell to run one after another. Any command sequence you've typed more than a couple of times deserves to become a script.

Write a script

Create hello.sh with an editor such as nano or vim:

bash
#!/bin/bash
# My first script
echo "Hello, $USER!"
echo "Today is $(date +%F) and you are in $(pwd)"
  • The first line, #!/bin/bash, is the shebang: it tells the system which program runs the file. #!/usr/bin/env bash is also common; it finds bash through PATH.
  • Lines starting with # are comments and are not executed.

Run it

bash
chmod +x hello.sh   # needed once: make it executable
./hello.sh          # run it; ./ means "in this directory"

Or hand it to bash without the execute permission:

bash
bash hello.sh
Note

Both ways run the script in a child process, so cd and variables inside it don't affect your terminal. If you need that, use source hello.sh (see "Processes" in the Basics).

Where to keep scripts

Put your everyday scripts in ~/bin and add it to PATH; then you can run them by name from anywhere:

bash
mkdir -p ~/bin
mv hello.sh ~/bin/hello
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
hello
02

Variables and quoting

Defining and using variables

bash
name="Alice"            # no spaces around = !
count=3
echo "$name has $count apples"
echo "${name}_backup"   # braces mark where the name ends

name = "Alice" fails, because the shell treats name as a command.

Capturing command output

bash
today=$(date +%F)
files=$(ls | wc -l)
echo "$today: $files files"

Integer arithmetic

bash
a=7; b=3
echo $((a + b))   # 10
echo $((a / b))   # 2 (integers only)
((count++))       # increment

For decimals use bc: echo "scale=2; 7/3" | bc.

Quoting: the most important habit

  • Single quotes keep everything literal: echo '$HOME' prints $HOME.
  • Double quotes expand variables and $( ) but keep the result as one piece.
  • Without quotes, a variable's value is split on spaces and wildcards in it are expanded.
bash
file="my notes.txt"
cat $file      # wrong: becomes cat my notes.txt, two files
cat "$file"    # right

Rule: always write variables as "$var", unless you know exactly why not.

Read-only variables and defaults

bash
readonly VERSION="1.0"
name=${1:-world}         # world when no argument was given
echo "Hello, $name"
03

Script arguments

Scripts can take arguments, as in ./backup.sh docs photos. Inside the script, special variables hold them:

VariableMeaning
$0The script's own name
$1, $2 …The first, second … argument
$#Number of arguments
"$@"All arguments, each kept separate (the one you usually want)
"$*"All arguments joined into one string
bash
#!/bin/bash
echo "Script: $0"
echo "$# arguments"
for arg in "$@"; do
  echo "Argument: $arg"
done

Checking arguments

bash
#!/bin/bash
if [ $# -lt 1 ]; then
  echo "Usage: $0 <directory>..." >&2
  exit 1
fi

>&2 sends the message to standard error, the convention for reporting problems.

shift: one argument at a time

shift drops $1 and moves the others down:

bash
while [ $# -gt 0 ]; do
  echo "Processing $1"
  shift
done

Options with getopts

bash
#!/bin/bash
verbose=0
while getopts "vo:" opt; do
  case $opt in
    v) verbose=1 ;;
    o) output=$OPTARG ;;
    *) echo "Usage: $0 [-v] [-o file]" >&2; exit 1 ;;
  esac
done
shift $((OPTIND - 1))    # what remains are ordinary arguments
echo "verbose=$verbose output=$output rest: $*"
04

Conditions

if

bash
if [ -f config.yml ]; then
  echo "Found the config file"
elif [ -f config.example.yml ]; then
  cp config.example.yml config.yml
else
  echo "No config file" >&2
  exit 1
fi

if actually accepts any command: if it succeeds (exit status 0), the then part runs.

bash
if grep -q ERROR app.log; then
  echo "The log contains errors"
fi

Common tests

TestTrue when
-e pathThe path exists
-f pathIt is a regular file
-d pathIt is a directory
-r / -w / -x pathReadable / writable / executable
-s pathThe file exists and is not empty
-z "$s"The string is empty
-n "$s"The string is not empty
"$a" = "$b"Strings are equal (!= for not equal)
$a -eq $bIntegers are equal
-ne -lt -le -gt -geNot equal, less, less or equal, greater, greater or equal
! testNegation

[ ] versus [[ ]]

[ ] is the portable form; [[ ]] is bash's improved version and the better choice in bash scripts:

bash
[[ $name == a* ]]              # pattern matching
[[ $email =~ ^[^@]+@[^@]+$ ]]  # regular expressions
[[ -f $f && -r $f ]]           # && and || directly inside

Variables inside [[ ]] aren't split even without quotes, but quoting is still a good habit.

Numbers with (( ))

bash
if (( count > 10 )); then
  echo "Too many"
fi

case: many branches

bash
case "$1" in
  start)   echo "Starting" ;;
  stop)    echo "Stopping" ;;
  restart) echo "Restarting" ;;
  *.txt)   echo "A text file" ;;
  *)       echo "Usage: $0 {start|stop|restart}" ;;
esac

Short forms

bash
[ -d backup ] || mkdir backup
command -v git >/dev/null && echo "git is installed"
05

Loops

for: over a list of values

bash
for name in alice bob carol; do
  echo "Hello, $name"
done

for f in *.log; do            # over files
  gzip "$f"
done

for i in {1..5}; do           # a number sequence
  echo "Round $i"
done

for ((i = 0; i < 3; i++)); do # C style
  echo "$i"
done

while: as long as a condition holds

bash
count=1
while [ $count -le 3 ]; do
  echo "$count"
  ((count++))
done

Reading a file line by line

One of the most useful patterns:

bash
while IFS= read -r line; do
  echo "Read: $line"
done < names.txt
  • IFS= keeps leading and trailing spaces;
  • -r stops backslashes being treated as escapes.

It works on command output too:

bash
ps -ef | grep nginx | while read -r user pid rest; do
  echo "nginx process: $pid"
done

until: until a condition holds

bash
until ping -c 1 example.com >/dev/null; do
  echo "No network yet, retrying in 5 seconds"
  sleep 5
done

break and continue

bash
for f in *; do
  [ -d "$f" ] && continue   # skip directories
  [ "$f" = "STOP" ] && break
  echo "$f"
done
06

Functions

Wrap code you reuse in a function and your scripts get much clearer:

bash
#!/bin/bash

greet() {
  local name=$1          # local: only visible inside the function
  echo "Hello, $name"
}

greet Alice
greet Bob
  • Define a function before calling it;
  • arguments work like a script's: $1, $2, $@, $#;
  • variables are global by default; declare them local so you don't overwrite outside ones by accident.

Returning results

return only gives back an exit status from 0 to 255 (success or failure). To return data, echo it and capture it with $( ):

bash
is_number() {
  [[ $1 =~ ^[0-9]+$ ]]       # the last command's status becomes the function's
}

square() {
  echo $(( $1 * $1 ))
}

if is_number "$1"; then
  result=$(square "$1")
  echo "$1 squared is $result"
fi

A practical example

bash
log() {
  echo "[$(date +%T)] $*" >&2
}

die() {
  log "error: $*"
  exit 1
}

[ -f "$1" ] || die "file $1 not found"
log "processing $1"
07

Exit status and error handling

Exit status

Every command finishes with an exit status: 0 for success, any other number for failure.

bash
cp a.txt b.txt
echo $?        # 0 on success, non-zero on failure

A script ends with exit N to return a status. Without an exit, the script's status is that of its last command.

Stop on errors: set -euo pipefail

By default, when a command in a script fails, the script just carries on, which can make things worse. Put this at the top:

bash
#!/bin/bash
set -euo pipefail
OptionEffect
-eExit as soon as any command fails
-uTreat unset variables as errors (so rm -rf "$dir/" can't run with an empty dir)
-o pipefailA pipeline fails if any command in it fails

When a command is allowed to fail, write command || true.

trap: clean up on exit

bash
#!/bin/bash
set -euo pipefail
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT     # remove the temp dir however the script ends

cd "$tmp"
# ... do some work ...

trap can also catch signals, e.g. trap 'echo interrupted' INT runs when you press Ctrl+C. See mktemp.

Debugging

bash
bash -n script.sh     # check the syntax only
bash -x script.sh     # print every command as it runs

Inside a script, set -x turns tracing on and set +x turns it off.

08

Practical tips

Check scripts with ShellCheck

ShellCheck finds common mistakes such as missing quotes and syntax slips. Run it on every script:

bash
sudo apt install shellcheck
shellcheck backup.sh

Check that a command exists

bash
if ! command -v jq >/dev/null; then
  echo "Please install jq first" >&2
  exit 1
fi

Multi-line text: here documents

bash
cat << END
Usage: $0 [options] file
  -v  verbose output
  -h  show this help
END

Handle file names safely

bash
# names may contain spaces: always quote
for f in *.txt; do
  mv -- "$f" "backup/$f"
done

# with find and xargs, use -print0 / -0
find . -name "*.tmp" -print0 | xargs -0 rm --

-- tells a command "everything after this is a file name, not an option", so names starting with - can't be mistaken for options.

Confirm before doing something dangerous

bash
read -r -p "Really delete $dir? [y/N] " answer
[[ $answer == [yY] ]] || exit 0
rm -rf -- "$dir"

A complete example: back up a directory

bash
#!/bin/bash
set -euo pipefail

src=${1:?usage: $0 <directory to back up>}
dest=~/backups
mkdir -p "$dest"

name="$(basename "$src")-$(date +%Y%m%d-%H%M%S).tar.gz"
tar -czf "$dest/$name" -C "$(dirname "$src")" "$(basename "$src")"
echo "Backed up to $dest/$name"

# keep only the 7 most recent backups
ls -1t "$dest"/*.tar.gz | tail -n +8 | xargs -r rm --

Commands used: tar, basename, dirname, xargs.

More shell scripting topics are on the way.