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:-ffile,-dfolder,-zempty 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
set -euo pipefailat the top.- Always quote variables.
- Check scripts with
shellcheck, a tool that finds typical mistakes. - For more than about a hundred lines or complex data, prefer Python.
See also: Bash, grep, sed and awk: editing text in the terminal