ubuntu, updated

Bash scripting basics

Your first Bash script: the shebang, variables, arguments, if, loops and exit codes. Just enough to automate admin tasks.

When to script

Script it when you do the same thing a third time, or when a task has more than a few steps and must be done the same way every time (backups, cleanup, user setup, health checks). A Bash script is just the commands you would type, saved in a file.

Your first script

#!/bin/bash
# Purpose: say hello and show disk usage of /
echo "Hello from $(hostname)"
df -h /
sudo chmod +x /usr/local/bin/hello.sh     # make it executable
hello.sh                                  # run it (/usr/local/bin is in PATH)
bash -n hello.sh                          # only check the syntax
bash -x hello.sh                          # run and show every command (debugging)

Variables

NAME="web01"                 # no spaces around =
echo "Server: $NAME"         # use with $
TODAY=$(date +%F)            # store a command's output
echo "Backup-${TODAY}.tar.gz"   # ${} when text follows directly

Always put variables in double quotes: "$NAME". Without quotes, a value with spaces breaks into several words.

Arguments

VariableContains
$1, $2…First, second… argument
$#Number of arguments
"$@"All arguments
$0Name of the script
$?Exit code of the last command
#!/bin/bash
if [[ $# -ne 1 ]]; then
  echo "Usage: $0 USERNAME" >&2
  exit 1
fi
id "$1"

if

if [[ -f /etc/nginx/nginx.conf ]]; then
  echo "nginx is configured"
elif [[ -d /etc/apache2 ]]; then
  echo "apache found"
else
  echo "no web server"
fi
TestTrue if
[[ -f FILE ]] / [[ -d DIR ]]file / directory exists
[[ -z "$VAR" ]]variable is empty
[[ "$A" == "$B" ]]strings are equal
[[ $N -gt 10 ]]number greater than (-lt, -eq, -ge, -le, -ne)
! [[ ... ]]negation

You can also test a command directly: if systemctl is-active --quiet nginx; then ....

Loops

for USER in anna ben carla; do
  sudo adduser --disabled-password --gecos "" "$USER"
done

for FILE in /var/log/app/*.log; do
  gzip "$FILE"
done

while read -r LINE; do
  echo "Host: $LINE"
done < hosts.txt

Exit codes

Every command returns a number: 0 = success, anything else = error. Your script should do the same with exit 0 / exit 1, so cron, systemd and other scripts know whether it worked.

cp /etc/fstab /root/fstab.bak || { echo "Backup failed" >&2; exit 1; }

Functions

log() {
  echo "$(date '+%F %T') $*"
}

log "Starting cleanup"

Next: Script best practices.

§ home
~/knubertus/home/
1,1 Top