Sikau

Linux and the shell · Day 14 · about 45 min

Shell scripting

Shebang, arguments, if, loops, functions and exit codes.

Automate the boring parts

Anything you type twice can become a shell script: a file of commands with variables, conditions and loops. Deploys, backups and health checks are usually just Bash.

A real script

#!/usr/bin/env bash
set -euo pipefail

name="${1:-world}"
count=${2:-2}

greet() {
  local who="$1"
  echo "Hello, $who!"
}

if [[ $count -gt 3 ]]; then
  echo "That's a lot of greetings" >&2
  exit 1
fi

for i in $(seq 1 "$count"); do
  greet "$name #$i"
done

for f in *.txt; do
  [ -f "$f" ] || continue
  echo "$f has $(wc -l < "$f") lines"
done
echo "done (args: $#)"

Always quote variables: "$file" keeps names with spaces in one piece.

The rest of this lesson

  • Strict mode explainedexplain
  • Tests and loopsexplain
  • Exit codepredict
  • Special variablesmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 16 lessons of Linux and the shell