Archive · Linux

Shell Scripting Basics

Variables, conditions, loops and exit codes, with the three lines every script should start with.

1 min read

  • Ubuntu 18.04.3 LTS
  • bash 4.4

A script is a text file of commands. Start safe:

#!/usr/bin/env bash
set -euo pipefail          # stop on errors, unset variables and failed pipes

A small, useful example that checks disk usage:

#!/usr/bin/env bash
set -euo pipefail
THRESHOLD=80
usage=$(df --output=pcent / | tail -1 | tr -dc '0-9')

if [ "$usage" -ge "$THRESHOLD" ]; then
  echo "Disk is ${usage}% full" >&2
  exit 1
fi
echo "Disk ok: ${usage}%"

Every command returns an exit code: 0 means success and anything else means failure. $? holds the last one, and if, && and || use it. Quote your variables ("$file"), because unquoted values containing spaces are the classic scripting bug. Run shellcheck script.sh to catch such mistakes.