Bash scripting essentials
Variables, conditions, loops and exit codes: write a script you can trust.
A Bash script is a text file of commands. Start it with a shebang line so the system knows which interpreter to use, and make it executable.
#!/usr/bin/env bash
set -euo pipefail
src="${1:?usage: backup.sh SOURCE_DIR}"
stamp="$(date +%F)"
tar -czf "backup-$stamp.tar.gz" "$src"
echo "Saved backup-$stamp.tar.gz"chmod +x backup.sh
./backup.sh /home/ana/docsSafer defaults
set -estops the script when a command fails.set -utreats an unset variable as an error.set -o pipefailmakes a pipeline fail if any command in it fails.- Quote variables:
"$src". Unquoted values are split on spaces and can break on file names with spaces.
Conditions and loops
if [[ -f "$file" ]]; then
echo "exists"
elif [[ -d "$file" ]]; then
echo "directory"
else
echo "missing"
fi
for f in *.log; do
gzip "$f"
doneExit codes
Every command returns a number: 0 means success and anything else means failure. $? holds the last one, and && and || chain commands on it.
mkdir build && cd build
grep -q ERROR app.log || echo "no errors"NoteUse shellcheck script.sh (a free linter) to find quoting mistakes and portability problems before they hurt you.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.