Parsing Script Arguments
A script receives its command-line arguments as a plain list of strings in $1, $2 and so on (lesson 42). Bash does not know which of them are options, which are values for options and which are file names; it is the script's job to work that out. This process is called argument parsing. A script that parses its arguments well accepts the same forms users already know from tools like ls, grep and cp, reports mistakes clearly and treats unusual file names safely.
This lesson explains the conventions that command-line arguments follow and builds a parsing loop with while, case and shift that handles all of them. The lessons that follow go deeper into individual parts: validating required arguments (128), optional arguments (129), the getopts builtin (130), help messages (131), defaults (132) and invalid input (133).
What the Script Actually Receives
Before parsing anything, it helps to look at the raw list. This small script prints the number of arguments and each argument in brackets:
printf 'argc=%d\n' "$#"
i=0
for a in "$@"; do i=$((i+1)); printf '%d: [%s]\n' "$i" "$a"; done
bash show.sh -v --output=report.txt -n 5 "my file.txt" -- -odd
argc=7
1: [-v]
2: [--output=report.txt]
3: [-n]
4: [5]
5: [my file.txt]
6: [--]
7: [-odd]
By the time the script runs, the shell has already removed the quotes, so "my file.txt" arrives as one argument containing a space. Everything else, such as whether 5 belongs to -n or whether -- means anything, is left to the script.
The Conventions Users Expect
Most Unix-like command-line tools follow the same rules, partly from the POSIX utility guidelines and partly from GNU conventions:
- Short options are a dash and one letter:
-v,-l. - Long options are two dashes and a word:
--verbose,--lines. - Option arguments are values that belong to an option. A short option takes its value as the next argument (
-o out.txt) or attached to it (-oout.txt). A long option takes it as the next argument (--output out.txt) or after an equals sign (--output=out.txt). - Bundled short options: several short options without values can be combined, so
-lwmeans-l -w. - Operands are the arguments that are not options, usually file names or other objects the command acts on.
--ends the options. Everything after it is an operand, even if it starts with a dash. This is how a user passes a file named-data.txt.- A single
-is an operand, and by convention means standard input (or standard output, depending on the position).
GNU tools also accept options after operands (ls a.txt -l), while strict POSIX parsing stops at the first operand. The loop in this lesson follows the GNU style; lesson 130 shows the POSIX style with getopts.
Simple Case: Arguments by Position
When a script takes a fixed number of operands and no options, there is nothing to parse; each argument has a meaning given by its position:
src=$1
dest=$2
echo "copy from [$src] to [$dest]"
copy from [notes.txt] to [backup/]
copy from [notes.txt] to []
The second run was missing the destination, and the script silently used an empty string. Positional scripts are simple, but they must check the number of arguments, which lesson 128 covers in detail.
Why a for Loop Is Not Enough
A for arg in "$@" loop visits each argument once, which works for options without values. It cannot handle an option followed by its value, because the loop has no way to consume the next argument:
for arg in "$@"; do
case $arg in
-v) echo "verbose" ;;
-o) echo "output... but which value?" ;;
*) echo "operand: $arg" ;;
esac
done
verbose
output... but which value?
operand: out.txt
operand: a.txt
out.txt was meant to be the value of -o, but the loop treated it as a file to process. Parsing needs a loop that can look at the current argument and take the one after it.
The while, case and shift Loop
The standard solution is a while loop that always inspects $1, decides what it is, and removes it with shift (lesson 44). When an option needs a value, the loop reads $2 and shifts once more:
#!/usr/bin/env bash
prog=${0##*/}
verbose=0
dry_run=0
output=
files=()
while (( $# > 0 )); do
case $1 in
-v|--verbose) verbose=1 ;;
-n|--dry-run) dry_run=1 ;;
-o|--output)
if (( $# < 2 )); then
printf '%s: option %s needs a value\n' "$prog" "$1" >&2; exit 2
fi
output=$2
shift ;;
--output=*) output=${1#*=} ;;
--) shift; files+=("$@"); break ;;
-*) printf '%s: unknown option: %s\n' "$prog" "$1" >&2; exit 2 ;;
*) files+=("$1") ;;
esac
shift
done
printf 'verbose=%s dry_run=%s output=[%s]\n' "$verbose" "$dry_run" "$output"
printf 'files (%d):' "${#files[@]}"
printf ' [%s]' "${files[@]}"
echo
How the Loop Works
while (( $# > 0 ))runs as long as arguments remain. Each pass handles the argument currently in$1.- The final
shiftafteresacremoves the argument that was just handled, so the next pass sees the following one. - Flags such as
-vonly set a variable. - Options with a value first check that a value exists (
$# < 2means$1is the last argument), copy$2, andshiftan extra time so the value is not processed again as an operand. --output=*matches the equals form.${1#*=}removes everything up to and including the first=, so--output=dir/a=b.txtcorrectly givesdir/a=b.txt.--shifts itself away, appends all remaining arguments to the operand list exactly as they are, and leaves the loop withbreak.-*catches every other argument that starts with a dash. Becausecasetries patterns from top to bottom (lesson 75), known options are matched first and only unknown ones reach this line.*collects operands into thefilesarray (lesson 99), which keeps names with spaces intact.
Running It
Options before, between and after operands all work:
$ bash parse.sh -v a.txt
verbose=1 dry_run=0 output=[]
files (1): [a.txt]
$ bash parse.sh a.txt --verbose b.txt
verbose=1 dry_run=0 output=[]
files (2): [a.txt] [b.txt]
The three forms of the output option give the same result:
$ bash parse.sh -o out.txt a.txt
verbose=0 dry_run=0 output=[out.txt]
files (1): [a.txt]
bash parse.sh --output out.txt a.txt and bash parse.sh --output=out.txt a.txt print the same two lines.
Mistakes are reported with status 2, the usual code for incorrect usage (lesson 116):
$ bash parse.sh -o
parse.sh: option -o needs a value
$ bash parse.sh -x a.txt
parse.sh: unknown option: -x
After --, an argument that looks like an option is treated as a file name:
$ bash parse.sh -- -v a.txt
verbose=0 dry_run=0 output=[]
files (2): [-v] [a.txt]
Values containing spaces survive, as long as the user quotes them and the script quotes its variables:
$ bash parse.sh -o "my report.txt" "a b.txt" c.txt
verbose=0 dry_run=0 output=[my report.txt]
files (2): [a b.txt] [c.txt]
What This First Version Does Not Handle
Testing reveals three gaps:
$ bash parse.sh -vn a.txt
parse.sh: unknown option: -vn
$ bash parse.sh -
parse.sh: unknown option: -
$ bash parse.sh -o -v a.txt
verbose=0 dry_run=0 output=[-v]
files (1): [a.txt]
Bundled options are rejected, a lone - is mistaken for an option, and an option value that starts with a dash is accepted as the value. The last one is normal behavior: many standard tools also take the next argument as the value without checking it, which is the only way to pass a value that really does start with a dash. The first two are fixed in the complete example below. With no operands at all, printf ' [%s]' still prints [] once, because printf runs its format once even with no arguments; the complete example avoids this by giving the file list a default.
Splitting Bundled Short Options
Bundled options like -lw can be supported by rewriting the argument list: replace -lw with -l followed by -w, then let the loop process the result. The expansions ${1:0:2} (the first two characters) and ${1:2} (everything after them) do the splitting, and set -- replaces the positional parameters:
set -- -lw a.txt
echo "before: $*"
set -- "${1:0:2}" "-${1:2}" "${@:2}"
echo "after: $*"
before: -lw a.txt
after: -l -w a.txt
"${@:2}" keeps all remaining arguments unchanged. Inside the parsing loop, the case for this rewrite must be followed by continue instead of falling through to shift, so the loop processes the new $1 (-l) on its next pass. A bundle of three letters is split one letter at a time over several passes. Options that take a value need care: -ofile means -o with the value file, not -o -f -i -l -e, so a pattern for the attached form (-o?*) must appear before the bundling pattern.
A Complete Example
wc2.sh counts lines and words, like a small version of wc. It supports short and long options, bundling, attached and separate option values, --, - for standard input, and an output file. It uses the usage conventions from lesson 125: errors in the arguments print a short message and a Try '... --help' line on standard error and exit with 2, while --help prints usage on standard output and exits with 0.
#!/usr/bin/env bash
# wc2.sh [-l] [-w] [-o FILE] [--] [FILE...]: count lines and/or words
set -euo pipefail
prog=${0##*/}
usage() { printf 'usage: %s [-l] [-w] [-o FILE] [--] [FILE...]\n' "$prog"; }
bad_usage() {
printf '%s: %s\n' "$prog" "$*" >&2
printf "Try '%s --help' for more information.\n" "$prog" >&2
exit 2
}
lines=0 words=0 output=
files=()
while (( $# > 0 )); do
case $1 in
-h|--help) usage; exit 0 ;;
-l|--lines) lines=1 ;;
-w|--words) words=1 ;;
-o|--output)
(( $# >= 2 )) || bad_usage "option '$1' requires an argument"
output=$2
shift ;;
-o?*) output=${1#-o} ;;
--output=*) output=${1#*=} ;;
--) shift; files+=("$@"); break ;;
-) files+=("-") ;;
-[!-]?*) # bundled short options: -lw becomes -l -w
set -- "${1:0:2}" "-${1:2}" "${@:2}"
continue ;;
-*) bad_usage "unrecognized option '$1'" ;;
*) files+=("$1") ;;
esac
shift
done
# no -l and no -w: count both
(( lines || words )) || { lines=1; words=1; }
(( ${#files[@]} > 0 )) || files=("-")
count() { # count FILE ("-" means standard input)
local name=$1 counts l w
if [[ $1 == - ]]; then
name="(stdin)"
counts=$(wc -lw)
else
counts=$(wc -lw < "$1") || return 1
fi
read -r l w <<< "$counts"
local out=$name
(( lines )) && out+=" lines=$l"
(( words )) && out+=" words=$w"
printf '%s\n' "$out"
}
status=0
if [[ -n $output ]]; then
exec > "$output"
fi
for f in "${files[@]}"; do
count "$f" || status=1
done
exit "$status"
How the Pieces Fit
- The order of the
casepatterns matters.-o?*(an-owith something attached) comes before-[!-]?*(any other single-dash argument longer than two characters), so-oout.txtis read as a value while-lwis split.-)comes before-*, so a lone dash is an operand.-[!-]?*cannot match a long option, because its second character must not be a dash. - Parsing only collects information. The loop sets variables and fills an array; the real work starts after it. Keeping these phases apart makes the script easier to read and makes it possible to check combinations of options before doing anything (lesson 128).
- Defaults are applied after parsing: with neither
-lnor-wthe script counts both, and with no files it reads standard input. Lesson 132 covers defaults in detail. exec > "$output"redirects the standard output of the rest of the script into the file (lesson 115 showedexecwith logs), so the counting code does not need to know where its output goes.- Each file is counted separately, and a failure on one file sets the final status to 1 without stopping the others.
Running the Complete Example
With a.txt holding two lines and three words, b c.txt holding one line of three words, and a file named -data.txt:
$ bash wc2.sh a.txt
a.txt lines=2 words=3
$ bash wc2.sh -l a.txt
a.txt lines=2
$ bash wc2.sh -wl a.txt
a.txt lines=2 words=3
$ bash wc2.sh -w "b c.txt" a.txt
b c.txt words=3
a.txt words=3
$ bash wc2.sh -- -data.txt
-data.txt lines=1 words=1
The output options, run one after another, created three files:
$ bash wc2.sh -lo out1.txt a.txt # out1.txt: a.txt lines=2
$ bash wc2.sh -oout2.txt a.txt # out2.txt: a.txt lines=2 words=3
$ bash wc2.sh --output=out3.txt -w a.txt # out3.txt: a.txt words=3
In the first one, -lo was split into -l and -o, and -o then took out1.txt as its value.
Reading standard input, alone or with - among other files:
$ printf 'a b\nc\n' | bash wc2.sh -l
(stdin) lines=2
$ printf 'a b\nc\n' | bash wc2.sh a.txt -
a.txt lines=2 words=3
(stdin) lines=2 words=3
Usage errors and file errors are reported differently:
$ bash wc2.sh -lx a.txt
wc2.sh: unrecognized option '-x'
Try 'wc2.sh --help' for more information.
$ bash wc2.sh a.txt missing.txt
a.txt lines=2 words=3
wc2.sh: line 47: missing.txt: No such file or directory
The first ended with status 2 and processed nothing, because the command line itself was wrong. The second ended with status 1 after processing the file that existed; the error line is Bash's own message for the failed < redirection, which already names the file and the reason.