Script Arguments & getopts
Scripts become reusable tools when they accept arguments: ./backup.sh -v -d /mnt/usb photos docs. Bash gives you the arguments in positional parameters ($1, $2, …), and the built-in getopts parses short options like -v and -d DIR for you.
Positional parameters
cat > greet.sh <<'SCRIPT'
#!/usr/bin/env bash
echo "script: $0"
echo "count: $#"
echo "first: ${1:-<none>}"
echo "second: ${2:-<none>}"
echo "all: $*"
SCRIPT
bash greet.sh Ada "Grace Hopper" Linus
echo "---"
bash greet.shscript: greet.sh
count: 3
first: Ada
second: Grace Hopper
all: Ada Grace Hopper Linus
---
script: greet.sh
count: 0
first: <none>
second: <none>
all:
| Parameter | Meaning |
|---|---|
$0 |
How the script was called |
$1 … $9, ${10} |
Arguments (braces needed from 10 up) |
$# |
Number of arguments |
"$@" |
All arguments, each as its own word |
"$*" |
All arguments joined into one string |
In this lesson the scripts are written to files and run with arguments. Inside one script you can also replace the positional parameters with set -- a b c, which is handy for trying things out.
Checking arguments
A good script validates its input and prints a usage message when it's wrong:
cat > resize.sh <<'SCRIPT'
#!/usr/bin/env bash
usage() { echo "Usage: $(basename "$0") WIDTH FILE..." >&2; exit 2; }
(( $# >= 2 )) || usage
width=$1
shift
[[ $width =~ ^[0-9]+$ ]] || { echo "error: WIDTH must be a number, got '$width'" >&2; exit 2; }
for file in "$@"; do
echo "resizing $file to ${width}px"
done
SCRIPT
bash resize.sh 800 a.png "b c.png"
bash resize.sh
echo "status: $?"
bash resize.sh wide a.png
echo "status: $?"resizing a.png to 800px
resizing b c.png to 800px
Usage: resize.sh WIDTH FILE...
status: 2
error: WIDTH must be a number, got 'wide'
status: 2
shift drops $1 and moves every argument down one place, so after it "$@" contains only the files. shift 2 drops two.
Looping with shift
while (( $# > 0 )) plus shift processes arguments one at a time, which also works for long options like --verbose:
set -- --name report --verbose -- -strange-file.txt data.csv
verbose=0; name="default"; files=()
while (( $# > 0 )); do
case $1 in
-v|--verbose) verbose=1 ;;
-n|--name) name=$2; shift ;;
--) shift; files+=("$@"); break ;;
-*) echo "unknown option: $1" >&2; exit 2 ;;
*) files+=("$1") ;;
esac
shift
done
echo "verbose=$verbose name=$name"
printf 'file: %s\n' "${files[@]}"verbose=1 name=report
file: -strange-file.txt
file: data.csv
-- conventionally means "end of options": everything after it is a plain argument, even if it starts with -.
getopts: standard short options
getopts OPTSTRING VAR parses options one per call. In OPTSTRING, each letter is an allowed option; a letter followed by : takes a value, which arrives in $OPTARG:
cat > backup.sh <<'SCRIPT'
#!/usr/bin/env bash
verbose=0
dest="/backups"
level=6
while getopts ":vd:l:h" opt; do
case $opt in
v) verbose=1 ;;
d) dest=$OPTARG ;;
l) level=$OPTARG ;;
h) echo "Usage: backup.sh [-v] [-d DEST] [-l LEVEL] SOURCE..."; exit 0 ;;
:) echo "error: -$OPTARG needs a value" >&2; exit 2 ;;
?) echo "error: unknown option -$OPTARG" >&2; exit 2 ;;
esac
done
shift $(( OPTIND - 1 ))
echo "verbose=$verbose dest=$dest level=$level"
echo "sources: $*"
SCRIPT
bash backup.sh -v -d /mnt/usb photos docs
bash backup.sh -l9 -vd /tmp music
bash backup.sh -x photos
bash backup.sh -dverbose=1 dest=/mnt/usb level=6
sources: photos docs
verbose=1 dest=/tmp level=9
sources: music
error: unknown option -x
error: -d needs a value
How it works:
- The loop runs once per option.
-l9and-vd /tmpshow that combined and attached forms are handled automatically. - A leading
:in the option string enables "silent" error handling: unknown options give?and a missing value gives:, with the option letter in$OPTARG, so you print your own messages. OPTINDis the index of the next argument to process;shift $((OPTIND - 1))removes the parsed options, leaving the remaining arguments in"$@".
Note:
getoptsonly supports short options (-v). For long options (--verbose) use thewhile/case/shiftloop above, or the externalgetopttool from util-linux.
Reading options from the environment
Not every setting has to be an option. Environment variables with defaults are common for configuration:
cat > deploy.sh <<'SCRIPT'
#!/usr/bin/env bash
: "${DEPLOY_ENV:=staging}"
: "${REPLICAS:=2}"
echo "deploying to $DEPLOY_ENV with $REPLICAS replicas"
SCRIPT
bash deploy.sh
DEPLOY_ENV=production REPLICAS=5 bash deploy.shdeploying to staging with 2 replicas
deploying to production with 5 replicas
: "${VAR:=default}" assigns the default if the variable is unset (: is a command that does nothing). VAR=value command sets the variable only for that one command.
Test yourself
In a script called with ./s.sh a b c, what is $#?
- 0
- 3
- 4
- a b c
In getopts "ab:" opt, what does b: mean?
- -b is required
- -b takes a value, available in $OPTARG
- -b is a long option
- -b ends option parsing
What does shift do?
- Deletes the script
- Removes $1 and moves the remaining arguments down
- Moves the cursor
- Swaps $1 and $2