Written for bash 5. macOS includes bash 3.2, so anything marked bash 4 or later needs a newer bash from Homebrew; zsh, the default macOS shell, runs most of this but not all of it. On Windows, WSL gives you a real Linux, so everything marked Linux works there. Git Bash, which comes with Git for Windows, runs everything marked Windows; it doesn't include tools such as bc, flock, nc or cron, and its ping is the Windows one. Save scripts with Unix (LF) line endings, or bash will fail with errors about \r. Snippets that span several lines go in a script file. Names such as backup.sh, web01 and hosts.txt are examples.

Start a script #

  • Get bash on Windows with Git Bash (run in PowerShell)Windows
    winget install --id Git.Git -e
  • Get a full Linux with bash on Windows using WSL (run in PowerShell as admin)Windows
    wsl --install
  • Start a script with the bash shebang lineLinux, macOS, Windows
    #!/usr/bin/env bash
  • Stop the script on errors, unset variables and failed pipesLinux, macOS, Windows
    set -euo pipefail
  • A good starting template for a new scriptLinux, macOS, Windows
    #!/usr/bin/env bash set -euo pipefail script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" main() { echo "Running from $script_dir" } main "$@"
  • Make a script executableLinux, macOS
    chmod +x backup.sh
  • Run a script in the current folderLinux, macOS, Windows
    ./backup.sh
  • Run a script without making it executableLinux, macOS, Windows
    bash backup.sh
  • Run a script in the current shell, so its variables stay setLinux, macOS, Windows
    source ./env.sh
  • Check a script for syntax errors without running itLinux, macOS, Windows
    bash -n backup.sh
  • Show each command as the script runs it, to debugLinux, macOS, Windows
    bash -x backup.sh
  • Turn on debugging for just part of a scriptLinux, macOS, Windows
    set -x cp "$src" "$dest" set +x
  • Check a script for common mistakes with ShellCheckLinux, macOS, Windows
    shellcheck backup.sh
  • Install ShellCheck
    Debian, Ubuntu
    sudo apt install shellcheck
    Red Hat, Fedora
    sudo dnf install ShellCheck
    Alpine
    apk add shellcheck
    macOS
    brew install shellcheck
    Windows
    winget install --id koalaman.shellcheck
  • Check which version of bash you haveLinux, macOS, Windows
    bash --version
  • Install a current bash on macOS, which includes bash 3.2macOS
    brew install bash
  • Get the folder the script is in, wherever it's run fromLinux, macOS, Windows
    script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  • Add a commentLinux, macOS, Windows
    # Rotate logs older than 7 days

Variables #

  • Set a variable (no spaces around the =)Linux, macOS, Windows
    name="web01"
  • Use a variableLinux, macOS, Windows
    echo "Connecting to $name"
  • Use a variable right next to other textLinux, macOS, Windows
    echo "${name}_backup.tar.gz"
  • Quote variables so spaces in names don't break commandsLinux, macOS, Windows
    cp "$file" "$dest"
  • Save a command's output in a variableLinux, macOS, Windows
    today=$(date +%F)
  • Use a default value if a variable is empty or unsetLinux, macOS, Windows
    port="${PORT:-8080}"
  • Stop with an error if a variable isn't setLinux, macOS, Windows
    : "${API_TOKEN:?API_TOKEN must be set}"
  • Make a variable available to programs the script runsLinux, macOS, Windows
    export AWS_PROFILE=prod
  • Make a variable read-onlyLinux, macOS, Windows
    readonly CONFIG=/etc/app.conf
  • Delete a variableLinux, macOS, Windows
    unset name
  • Ask the user for a valueLinux, macOS, Windows
    read -rp "Hostname: " host
  • Ask for a password without showing itLinux, macOS, Windows
    read -rsp "Password: " password echo
  • Load settings from a file of KEY=value linesLinux, macOS, Windows
    source ./config.env
  • Get the exit code of the last command (0 means success)Linux, macOS, Windows
    echo $?
  • Get the script's name, its process ID and the last background job's IDLinux, macOS, Windows
    echo "$0 $$ $!"
  • Get the user, home folder and host nameLinux, macOS
    echo "$USER $HOME $HOSTNAME"

Arguments and options #

  • Use the first and second argumentsLinux, macOS, Windows
    src="$1" dest="$2"
  • Pass on all the arguments, keeping each one wholeLinux, macOS, Windows
    "$@"
  • Count the argumentsLinux, macOS, Windows
    echo $#
  • Show usage and stop if an argument is missingLinux, macOS, Windows
    if [[ $# -lt 1 ]]; then echo "Usage: $0 <host>" >&2 exit 1 fi
  • Use a default if an argument isn't givenLinux, macOS, Windows
    host="${1:-localhost}"
  • Loop over every argumentLinux, macOS, Windows
    for arg in "$@"; do echo "$arg" done
  • Drop the first argument and move the rest downLinux, macOS, Windows
    shift
  • Read short options such as -v and -o file with getoptsLinux, macOS, Windows
    verbose=false output=out.txt while getopts ":vo:" opt; do case $opt in v) verbose=true ;; o) output="$OPTARG" ;; *) echo "Usage: $0 [-v] [-o file]" >&2; exit 1 ;; esac done shift $((OPTIND - 1))
  • Read long options such as --dry-run and --env prodLinux, macOS, Windows
    while [[ $# -gt 0 ]]; do case $1 in --dry-run) dry_run=true; shift ;; --env) env="$2"; shift 2 ;; -h|--help) echo "Usage: $0 [--dry-run] [--env name]"; exit 0 ;; *) echo "Unknown option: $1" >&2; exit 1 ;; esac done

Conditions #

  • If, elif and elseLinux, macOS, Windows
    if [[ $count -gt 100 ]]; then echo "high" elif [[ $count -gt 10 ]]; then echo "medium" else echo "low" fi
  • Check a file existsLinux, macOS, Windows
    if [[ -f "$file" ]]; then echo "found" fi
  • Check a folder existsLinux, macOS, Windows
    if [[ -d "$dir" ]]; then echo "found" fi
  • Do something only if a file or folder doesn't existLinux, macOS, Windows
    if [[ ! -e "$path" ]]; then mkdir -p "$path" fi
  • Check a file isn't emptyLinux, macOS, Windows
    [[ -s "$file" ]]
  • Check a file can be read, written or runLinux, macOS, Windows
    [[ -r "$file" ]] [[ -w "$file" ]] [[ -x "$file" ]]
  • Check one file is newer than anotherLinux, macOS, Windows
    [[ "$src" -nt "$backup" ]]
  • Check two strings are the same, or differentLinux, macOS, Windows
    [[ "$env" == "prod" ]] [[ "$env" != "prod" ]]
  • Check a string is empty, or not emptyLinux, macOS, Windows
    [[ -z "$name" ]] [[ -n "$name" ]]
  • Check a string matches a patternLinux, macOS, Windows
    [[ "$file" == *.log ]]
  • Check a string contains a wordLinux, macOS, Windows
    [[ "$line" == *error* ]]
  • Check a string matches a regular expressionLinux, macOS, Windows
    if [[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then echo "looks like an IPv4 address" fi
  • Compare numbersLinux, macOS, Windows
    (( count > 10 )) [[ $count -gt 10 ]]
  • Combine checks with and, orLinux, macOS, Windows
    [[ -f "$file" && -r "$file" ]] [[ "$env" == dev || "$env" == test ]]
  • Run a command only if the one before it workedLinux, macOS, Windows
    mkdir -p backup && cp app.conf backup/
  • Run a command only if the one before it failedLinux, macOS
    ping -c 1 web01 >/dev/null || echo "web01 is down"
  • Check a command is installedLinux, macOS, Windows
    if ! command -v jq >/dev/null; then echo "Install jq first" >&2 exit 1 fi
  • Stop unless the script is run as rootLinux, macOS
    if [[ $EUID -ne 0 ]]; then echo "Run this as root" >&2 exit 1 fi
  • Check whether a command workedLinux, macOS, Windows
    if grep -q "error" app.log; then echo "errors found" fi
  • Choose between several values with caseLinux, macOS, Windows
    case "$1" in start) start_app ;; stop) stop_app ;; restart) stop_app; start_app ;; *) echo "Usage: $0 {start|stop|restart}" >&2; exit 1 ;; esac
  • Ask yes or no before carrying onLinux, macOS, Windows
    read -rp "Continue? [y/N] " answer [[ "$answer" == [yY] ]] || exit 1

Loops #

  • Loop over a list of valuesLinux, macOS, Windows
    for host in web01 web02 db01; do echo "$host" done
  • Loop over filesLinux, macOS, Windows
    for file in *.log; do gzip "$file" done
  • Skip the loop when no files match, instead of using the pattern itselfLinux, macOS, Windows
    shopt -s nullglob
  • Loop over a range of numbersLinux, macOS, Windows
    for i in {1..10}; do echo "$i" done
  • Loop with a counterLinux, macOS, Windows
    for ((i = 0; i < 5; i++)); do echo "$i" done
  • Read a file line by lineLinux, macOS, Windows
    while IFS= read -r line; do echo "$line" done < hosts.txt
  • Loop over a command's output line by lineLinux, macOS
    while IFS= read -r user; do echo "$user" done < <(cut -d: -f1 /etc/passwd)
  • Loop over files from find, even with spaces in their namesLinux, macOS, Windows
    while IFS= read -r -d '' file; do echo "$file" done < <(find . -name "*.conf" -print0)
  • Loop while something is trueLinux, macOS, Windows
    while [[ ! -f /tmp/ready ]]; do sleep 2 done
  • Loop until a server answersLinux, macOS
    until ping -c 1 web01 >/dev/null; do sleep 5 done
  • Loop forever, every 60 secondsLinux, macOS, Windows
    while true; do df -h / sleep 60 done
  • Skip to the next item, or stop the loopLinux, macOS, Windows
    continue break
  • Retry a command up to 5 timesLinux, macOS, Windows
    for attempt in {1..5}; do curl -fsS https://example.com && break echo "Attempt $attempt failed" >&2 sleep 5 done

Functions #

  • Write a function and call itLinux, macOS, Windows
    greet() { echo "Hello $1" } greet web01
  • Keep a variable inside a functionLinux, macOS, Windows
    count_lines() { local file="$1" wc -l < "$file" }
  • Get a value back from a functionLinux, macOS, Windows
    count_files() { find "$1" -type f | wc -l } total=$(count_files /var/log)
  • Return success or failure from a functionLinux, macOS
    is_up() { ping -c 1 "$1" >/dev/null 2>&1 } if is_up web01; then echo "up" fi
  • Print timestamped log messagesLinux, macOS, Windows
    log() { echo "$(date +"%F %T") $*" } log "Backup started"
  • Print an error and stopLinux, macOS, Windows
    die() { echo "Error: $*" >&2 exit 1 } [[ -f "$config" ]] || die "No config file"
  • List the functions defined in the current shellLinux, macOS, Windows
    declare -F

Strings #

  • Get the length of a stringLinux, macOS, Windows
    echo "${#name}"
  • Get part of a string (from position 0, 5 characters)Linux, macOS, Windows
    echo "${name:0:5}"
  • Replace the first match in a stringLinux, macOS, Windows
    echo "${path/old/new}"
  • Replace every match in a stringLinux, macOS, Windows
    echo "${path//old/new}"
  • Get the file name from a pathLinux, macOS, Windows
    echo "${path##*/}"
  • Get the folder from a pathLinux, macOS, Windows
    echo "${path%/*}"
  • Remove the extension from a file nameLinux, macOS, Windows
    echo "${file%.*}"
  • Get the extension of a file nameLinux, macOS, Windows
    echo "${file##*.}"
  • Remove text from the start of a stringLinux, macOS, Windows
    echo "${version#v}"
  • Make a string UPPERCASE or lowercase (bash 4 or later)Linux, macOS, Windows
    echo "${name^^}" echo "${name,,}"
  • Split a string on commas into an arrayLinux, macOS, Windows
    IFS=, read -ra parts <<< "$csv"
  • Print text in neat columnsLinux, macOS, Windows
    printf '%-15s %5s\n' "$host" "$status"
  • Print coloured textLinux, macOS, Windows
    red=$'\e[31m' reset=$'\e[0m' echo "${red}Failed${reset}"
  • Repeat a character to make a lineLinux, macOS, Windows
    printf '%.0s-' {1..40}; echo

Arrays #

  • Make an arrayLinux, macOS, Windows
    hosts=(web01 web02 db01)
  • Add an item to an arrayLinux, macOS, Windows
    hosts+=(db02)
  • Get every item, each kept wholeLinux, macOS, Windows
    "${hosts[@]}"
  • Get one item (counting from 0)Linux, macOS, Windows
    echo "${hosts[0]}"
  • Count the itemsLinux, macOS, Windows
    echo "${#hosts[@]}"
  • Loop over an arrayLinux, macOS, Windows
    for host in "${hosts[@]}"; do echo "$host" done
  • Get a slice of an array (2 items from position 1)Linux, macOS, Windows
    echo "${hosts[@]:1:2}"
  • Remove an itemLinux, macOS, Windows
    unset 'hosts[1]'
  • Read a file's lines into an array (bash 4 or later)Linux, macOS, Windows
    mapfile -t hosts < hosts.txt
  • Join an array with commasLinux, macOS, Windows
    (IFS=,; echo "${hosts[*]}")
  • Make a key and value array (bash 4 or later)Linux, macOS, Windows
    declare -A ports=([ssh]=22 [http]=80 [https]=443)
  • Get a value by its keyLinux, macOS, Windows
    echo "${ports[ssh]}"
  • Loop over keys and valuesLinux, macOS, Windows
    for service in "${!ports[@]}"; do echo "$service ${ports[$service]}" done

Arithmetic #

  • Do whole-number mathsLinux, macOS, Windows
    total=$(( used + free ))
  • Add 1 to a counterLinux, macOS, Windows
    (( count++ ))
  • Get the remainder of a divisionLinux, macOS, Windows
    echo $(( 17 % 5 ))
  • Raise to a powerLinux, macOS, Windows
    echo $(( 2 ** 10 ))
  • Do maths with decimalsLinux, macOS
    echo "scale=2; 10 / 3" | bc
  • Get a random number from 0 to 99Linux, macOS, Windows
    echo $(( RANDOM % 100 ))
  • Work out a percentageLinux, macOS, Windows
    pct=$(( used * 100 / total ))

Output and redirection #

  • Write output to a file, replacing itLinux, macOS, Windows
    echo "started" > run.log
  • Add output to the end of a fileLinux, macOS, Windows
    echo "finished" >> run.log
  • Send errors to a fileLinux, macOS, Windows
    ./backup.sh 2> errors.log
  • Send output and errors to the same fileLinux, macOS, Windows
    ./backup.sh > run.log 2>&1
  • Throw away all outputLinux, macOS, Windows
    ./backup.sh >/dev/null 2>&1
  • Print a message as an errorLinux, macOS, Windows
    echo "Disk almost full" >&2
  • Show output on screen and save it to a fileLinux, macOS, Windows
    ./backup.sh | tee run.log
  • Send everything the script prints to a log file as wellLinux, macOS, Windows
    exec > >(tee -a /var/log/backup.log) 2>&1
  • Write a file from a block of text (here document)Linux, macOS, Windows
    cat > app.conf <<EOF host=$host port=$port EOF
  • Write a block of text without filling in variablesLinux, macOS, Windows
    cat > run.sh <<'EOF' echo "$HOME is not expanded here" EOF
  • Write to a file that needs rootLinux, macOS
    echo "10.0.0.5 web01" | sudo tee -a /etc/hosts >/dev/null
  • Pass a string to a command as its inputLinux, macOS, Windows
    grep -c "," <<< "$csv"
  • Compare the output of two commandsLinux, macOS, Windows
    diff <(sort old.txt) <(sort new.txt)

Errors, exit codes and cleanup #

  • Stop the script with success, or with an error codeLinux, macOS, Windows
    exit 0 exit 1
  • Let one command fail without stopping a set -e scriptLinux, macOS, Windows
    rm old.tmp || true
  • Get the exit code of each command in a pipeLinux, macOS, Windows
    curl -s "$url" | jq .name echo "${PIPESTATUS[@]}"
  • Make a temporary fileLinux, macOS, Windows
    tmp=$(mktemp)
  • Make a temporary folderLinux, macOS, Windows
    tmpdir=$(mktemp -d)
  • Always clean up when the script ends, even after an errorLinux, macOS, Windows
    tmp=$(mktemp) trap 'rm -f "$tmp"' EXIT
  • Run something when Ctrl-C is pressedLinux, macOS, Windows
    trap 'echo "Stopped"; exit 130' INT
  • Show the line number when a command failsLinux, macOS, Windows
    trap 'echo "Failed at line $LINENO" >&2' ERR
  • Stop a command if it runs longer than 30 secondsLinux, Windows
    timeout 30 curl -s https://example.com
  • Stop the script running twice at the same timeLinux
    exec 9>/tmp/backup.lock flock -n 9 || { echo "Already running" >&2; exit 1; }

Dates and times #

  • Get today's date as 2026-11-19Linux, macOS, Windows
    date +%F
  • Put a timestamp in a file nameLinux, macOS, Windows
    tar czf "backup-$(date +%Y%m%d-%H%M%S).tar.gz" /etc
  • Get the time in seconds since 1970 (Unix time)Linux, macOS, Windows
    date +%s
  • Get yesterday's date
    Linux, Windows
    date -d yesterday +%F
    macOS
    date -v-1d +%F
  • Show how long the script tookLinux, macOS, Windows
    echo "Took ${SECONDS}s"
  • Time a single commandLinux, macOS, Windows
    time ./backup.sh
  • Wait 5 secondsLinux, macOS, Windows
    sleep 5

Background jobs and parallel tasks #

  • Run a command in the backgroundLinux, macOS, Windows
    ./backup.sh &
  • Run several commands at once, then wait for them allLinux, macOS
    rsync -a /data web01:/data & rsync -a /data web02:/data & wait
  • Wait for one background job and get its exit codeLinux, macOS, Windows
    ./backup.sh & pid=$! wait "$pid" echo "Exit code $?"
  • Run a command on several servers over SSHLinux, macOS, Windows
    for host in web01 web02; do ssh "$host" "uptime" done
  • Wait until a port is openLinux, macOS
    until nc -z localhost 5432; do sleep 1 done
  • Keep a script running after you log outLinux, macOS
    nohup ./long-job.sh > job.log 2>&1 &
  • Run a script every night at 2am with cron (add with crontab -e)Linux, macOS
    0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1

Handy script snippets #

  • Back up a file with the date before changing itLinux, macOS, Windows
    cp "$file" "$file.$(date +%F).bak"
  • Delete files older than 7 daysLinux, macOS, Windows
    find /var/backups -name "*.tar.gz" -mtime +7 -delete

    Warning: Run it without -delete first to see what it would remove.

  • Warn when the root disk is over 90% fullLinux
    usage=$(df --output=pcent / | tail -1 | tr -dc '0-9') if (( usage > 90 )); then echo "Disk is ${usage}% full" >&2 fi
  • Check a website answers with HTTP 200Linux, macOS, Windows
    code=$(curl -s -o /dev/null -w "%{http_code}" https://example.com) [[ "$code" == 200 ]] || echo "Site returned $code"
  • Read a value from a JSON API with jqLinux, macOS, Windows
    name=$(curl -s https://api.github.com/repos/vim/vim | jq -r .full_name)
  • Check a list of hosts and report which are downLinux, macOS
    while IFS= read -r host; do ping -c 1 "$host" >/dev/null || echo "$host is down" done < hosts.txt
  • Make a passwordLinux, macOS, Windows
    openssl rand -base64 24
  • Rename every .txt file to .mdLinux, macOS, Windows
    for file in *.txt; do mv -- "$file" "${file%.txt}.md" done