EMZETT.
Login

Writing shell scripts

In short: A shell script is a text file of commands that the shell runs one after another. It automates recurring jobs: backups, clean-ups, installations.

The first script

#!/usr/bin/env bash
set -euo pipefail          # stop on errors, report undefined variables
 
name="${1:-World}"         # first argument or "World"
echo "Hello, $name!"

Save as hello.sh, make it executable (chmod +x hello.sh) and start with ./hello.sh Anna.

Building blocks

  • Variables: target="/tmp/test", use with "$target" (always in quotes, because of spaces).
  • Conditions: if test -f "$file"; then ... fi. Important tests: -f file, -d folder, -z empty text.
  • Loops: for f in *.txt; do echo "$f"; done.
  • Functions: backup() { cp "$1" "$1.bak"; }.
  • Return value: $? is 0 on success. With && and || you chain depending on it.

Good habits

  1. set -euo pipefail at the top.
  2. Always quote variables.
  3. Check scripts with shellcheck, a tool that finds typical mistakes.
  4. For more than about a hundred lines or complex data, prefer Python.

See also: Bash, grep, sed and awk: editing text in the terminal