shBash
IntermediateLesson 7 of 15

Script Arguments & getopts – Bash

$1, $@, $#, shift, default values and parsing options.

A script's arguments are in $1, $2 …, $0 is the script name, $# the count, $@ all arguments as individual words. With shift you move the list to the left. Always put $@ in quotes: "$@" keeps each argument as its own word, even with spaces; "$*" glues everything into one string.

#!/usr/bin/env bash
# gruss.sh  –  call: ./gruss.sh Ada "Grace Hopper"
echo "Script:      $0"
echo "Count:       $#"
echo "First:       $1"
echo "All:"
for name in "$@"; do
  echo "  - $name"
done

Check required arguments early and print usage instructions to stderr (>&2). Optional values get default values via ${n:-10}.

#!/usr/bin/env bash
if [[ $# -lt 1 ]]; then
  echo "Usage: $0 <file> [count]" >&2
  exit 2
fi
datei="$1"
anzahl="${2:-3}"
tail -n "$anzahl" "$datei"

For options like -v or -o datei there is the built-in getopts. A colon after the letter means "option expects a value":

#!/usr/bin/env bash
verbose=0; ausgabe="out.txt"
while getopts "vo:h" opt; do
  case "$opt" in
    v) verbose=1 ;;
    o) ausgabe="$OPTARG" ;;
    h) echo "Usage: $0 [-v] [-o file] input..."; exit 0 ;;
    *) exit 2 ;;
  esac
done
shift $((OPTIND - 1))            # remaining arguments (after the options)
echo "verbose=$verbose ausgabe=$ausgabe rest: $*"
WarningConvention: exit code 2 for incorrect usage, 1 for runtime errors. And: a file that starts with - is mistaken for an option – use -- as a separator (rm -- "$datei", grep -- "$muster" datei).
TipFor long options (--verbose) use case "$1" in --verbose) ...; shift ;; esac in a while loop – getopts only knows short options.