Handling Optional Arguments
An optional argument is one the user may leave out. The script must behave sensibly both when it is given and when it is not. That sounds simple, but "optional" covers several different shapes: an extra operand at the end of the command line, a flag that switches a behavior on, a flag that can be repeated to increase an effect, an option that may or may not carry a value, and an option that can appear many times to build a list. Each shape needs its own handling, and in each case the script needs a reliable way to tell "not given" apart from "given with an empty value".
This lesson covers each shape in turn and then combines them in one script. Lesson 132 focuses on choosing and applying default values once you know an argument was not given.
Optional Operands
The simplest optional argument is an operand that may or may not be present. A script that greets someone with an optional custom greeting can test the argument count:
name=$1
if (( $# >= 2 )); then
greeting=$2
echo "greeting given: [$greeting]"
else
echo "no greeting given"
fi
$# >= 2 asks whether a second argument exists at all, regardless of its content. Two other common tests answer different questions, and the difference shows when the second argument is an empty string:
[[ ${2+set} == set ]] && echo "\${2+set} says: given" || echo "\${2+set} says: not given"
[[ -n ${2-} ]] && echo "-n says: non-empty" || echo "-n says: empty or missing"
Run three ways, with all three tests in one script:
$ bash opt1.sh ana
no greeting given
${2+set} says: not given
-n says: empty or missing
$ bash opt1.sh ana hi
greeting given: [hi]
${2+set} says: given
-n says: non-empty
$ bash opt1.sh ana ''
greeting given: []
${2+set} says: given
-n says: empty or missing
(( $# >= 2 ))and${2+set}are true whenever the argument exists, even if it is empty.${2+set}expands tosetwhen$2is set and to nothing otherwise (lesson 45).[[ -n ${2-} ]]is true only when the argument exists and is non-empty. The-in${2-}keeps the test safe underset -u(lesson 120).
Which one is right depends on whether an empty value means something. For a greeting, an empty string probably should be treated like a missing one; for a prefix or a separator, an empty string can be a deliberate choice.
A Variable Number of Trailing Operands
When any number of extra operands may follow the required ones, shift away the required ones and keep the rest as an array:
target=$1
shift
extras=("$@")
echo "target=[$target] extras=${#extras[@]}"
for e in "${extras[@]}"; do echo " extra [$e]"; done
$ bash rest.sh srv1
target=[srv1] extras=0
$ bash rest.sh srv1 "a b" c
target=[srv1] extras=2
extra [a b]
extra [c]
With no extras, the array is empty and the loop body never runs. Copying "$@" into an array (lesson 104) keeps each argument intact, including the one with a space.
Boolean Flags
A flag is an option without a value: it is either present or absent. The usual implementation starts a variable at 0 and sets it to 1 when the flag appears:
ignore_case=0
...
-i) ignore_case=1 ;;
...
(( ignore_case )) && cmd+=(-i)
Using 0 and 1 lets the script test the flag with (( ignore_case )), which reads naturally and avoids string comparisons. Giving the flag twice simply sets the variable to 1 twice.
Counting Flags
Some flags mean "more" each time they appear. -v for verbosity is the classic example: -v shows some detail, -vv more, -vvv everything. Instead of setting the variable to 1, the parser adds 1:
verbose=0
while (( $# > 0 )); do
case $1 in
-v|--verbose) verbose=$((verbose + 1)) ;;
-q|--quiet) verbose=0 ;;
-v*) set -- "-v" "-${1:2}" "${@:2}"; continue ;;
*) break ;;
esac
shift
done
echo "verbose level: $verbose"
(( verbose >= 1 )) && echo "info: level 1 message"
(( verbose >= 2 )) && echo "debug: level 2 message"
(( verbose >= 3 )) && echo "trace: level 3 message"
exit 0
The -v* pattern splits bundles such as -vvv into separate -v arguments, using the technique from lesson 127. The script ends with exit 0 because its last && line would otherwise leave status 1 whenever the level is low.
$ bash verb.sh
verbose level: 0
$ bash verb.sh -v -v
verbose level: 2
info: level 1 message
debug: level 2 message
$ bash verb.sh -vvv
verbose level: 3
info: level 1 message
debug: level 2 message
trace: level 3 message
$ bash verb.sh --verbose -vv
verbose level: 3
...
$ bash verb.sh -vv -q
verbose level: 0
$ bash verb.sh -q -v
verbose level: 1
info: level 1 message
The last two runs show that the arguments are processed in order: -q resets the level, and any -v after it starts counting again.
Flags That Can Be Switched Off: "Last One Wins"
When a behavior can be switched on or off, scripts often provide both forms, such as --color and --no-color. Processing the arguments in order and letting each one overwrite the variable gives the "last one wins" rule that most tools follow. This is useful in practice: a wrapper script or an alias can set a default (--color), and the user can still override it by adding --no-color at the end of the command line.
Options with an Optional Value
GNU tools have a few options whose value is itself optional. ls describes one in its help text as --color[=WHEN]: the square brackets mean the =WHEN part may be left out. --color alone means "always", while --color=never or --color=auto choose explicitly.
The value of such an option can only be given with =. If --color never were allowed, the parser could not know whether never is the option's value or a file named never. A script implements this with two patterns, one for the bare option and one for the = form:
color=auto
while (( $# > 0 )); do
case $1 in
--color) color=always ;;
--color=*) color=${1#*=} ;;
--no-color) color=never ;;
*) echo "unknown: $1" >&2; exit 2 ;;
esac
shift
done
case $color in
always|never|auto) ;;
*) echo "invalid --color value '$color' (use always, never or auto)" >&2; exit 2 ;;
esac
if [[ $color == auto ]]; then
[[ -t 1 ]] && use=yes || use=no
else
[[ $color == always ]] && use=yes || use=no
fi
echo "color=$color use_color=$use"
$ bash color.sh
color=auto use_color=no
$ bash color.sh --color
color=always use_color=yes
$ bash color.sh --color=never
color=never use_color=no
$ bash color.sh --color --no-color
color=never use_color=no
$ bash color.sh --no-color --color=always
color=always use_color=yes
$ bash color.sh --color=sometimes
invalid --color value 'sometimes' (use always, never or auto)
$ bash color.sh --color never
unknown: never
There are three distinct states here: the option was not given (auto, decided by the environment), given without a value (always), or given with a value. auto uses [[ -t 1 ]] to check whether standard output is a terminal (lesson 72). The runs above were captured through a pipe, so auto turned color off; run in a real terminal, the same command printed color=auto use_color=yes.
The last run shows the ambiguity rule in action: never was not taken as a value, and because this small script accepts no operands, it was rejected.
Short options should not have optional values. With -c taking an optional value, -c 3 would be ambiguous in the same way, and getopts (lesson 130) does not support optional values at all.
Repeatable Options That Build a List
Some options can be given several times, with each occurrence adding a value: grep -e PATTERN -e PATTERN or --exclude=GLOB --exclude=GLOB. An array collects them:
patterns=()
excludes=()
while (( $# > 0 )); do
case $1 in
-e) patterns+=("$2"); shift ;;
--exclude=*) excludes+=("${1#*=}") ;;
*) break ;;
esac
shift
done
echo "patterns: ${#patterns[@]}"; printf ' [%s]\n' "${patterns[@]}"
echo "excludes: ${#excludes[@]}"; printf ' [%s]\n' "${excludes[@]}"
$ bash rep.sh -e error -e "time out" --exclude='*.gz' --exclude=old.log
patterns: 2
[error]
[time out]
excludes: 2
[*.gz]
[old.log]
The array keeps the values separate and in order, including the one with a space and the glob pattern, which must not be expanded at this stage. The user quoted '*.gz' so that the shell passed it unexpanded, and the script's quoted "${1#*=}" keeps it that way. (This short demo omits the missing-value check for -e; the complete example below includes it.)
"Last one wins" and "every one counts" are both valid designs for a repeated option. Choose one deliberately for each option and say which in the help text.
Recording Whether an Option Was Given
Often the variable's own value can show whether an option was given: an empty context means -c was not used, a 0 in verbose means no -v. This breaks down when the empty or zero value is itself a valid choice. A --prefix option that accepts an empty prefix, for example, cannot use an empty variable to mean "not given". In that case keep a separate marker:
prefix= prefix_given=0
...
--prefix=*) prefix=${1#*=}; prefix_given=1 ;;
...
if (( prefix_given )); then
echo "using prefix [$prefix]"
fi
Lesson 132 shows how to apply defaults only when such a marker says the user did not choose a value.
A Complete Example
search.sh is a small wrapper around grep that combines every shape from this lesson: a required but repeatable option (-e), a flag (-i), an option with a validated value that is used only when given (-c), a counter (-v), an option with an optional value plus a negative form (--color, --no-color), and optional operands (files, with standard input as the fallback).
#!/usr/bin/env bash
# search.sh [OPTIONS] -e PATTERN [-e PATTERN]... [FILE...]
set -euo pipefail
prog=${0##*/}
usage() {
cat <<USAGE
usage: $prog [OPTIONS] -e PATTERN [-e PATTERN]... [FILE...]
-e PATTERN pattern to search for (repeatable, at least one)
-i ignore case
-c N show N lines of context (default: none)
-v more detail on stderr (repeatable: -vv)
--color[=WHEN] color matches: always (the default for --color), never, auto
--no-color same as --color=never
With no FILE, read standard input.
USAGE
}
bad_usage() {
printf '%s: %s\n' "$prog" "$*" >&2
printf "Try '%s --help' for more information.\n" "$prog" >&2
exit 2
}
need_value() { (( $2 >= 2 )) || bad_usage "option '$1' requires an argument"; }
patterns=() # repeatable option: every -e adds one
ignore_case=0 # flag: present or absent
context= # optional value: empty means "not given"
verbose=0 # counter
color=auto # optional value with a default; last one wins
files=() # optional operands
while (( $# > 0 )); do
case $1 in
-h|--help) usage; exit 0 ;;
-e) need_value "$1" "$#"; patterns+=("$2"); shift ;;
-e?*) patterns+=("${1#-e}") ;;
-i) ignore_case=1 ;;
-c) need_value "$1" "$#"; context=$2; shift ;;
-c?*) context=${1#-c} ;;
-v) verbose=$((verbose + 1)) ;;
--color) color=always ;;
--color=*) color=${1#*=} ;;
--no-color) color=never ;;
--) shift; files+=("$@"); break ;;
-[!-]?*) set -- "${1:0:2}" "-${1:2}" "${@:2}"; continue ;;
-?*) bad_usage "unrecognized option '$1'" ;;
*) files+=("$1") ;;
esac
shift
done
(( ${#patterns[@]} > 0 )) || bad_usage "at least one -e PATTERN is required"
case $color in always|never|auto) ;; *) bad_usage "invalid --color value '$color'" ;; esac
if [[ -n $context && ! $context =~ ^[0-9]{1,3}$ ]]; then
bad_usage "context must be a number from 0 to 999, got '$context'"
fi
# Build the grep command from what was (and was not) given
cmd=(grep -H -n --color="$color")
(( ignore_case )) && cmd+=(-i)
[[ -n $context ]] && cmd+=(-C "$((10#$context))")
for p in "${patterns[@]}"; do cmd+=(-e "$p"); done
cmd+=(--)
if (( ${#files[@]} > 0 )); then cmd+=("${files[@]}"); else cmd+=(-); fi
(( verbose >= 1 )) && printf '%s: %d pattern(s), %d file(s)\n' "$prog" "${#patterns[@]}" "${#files[@]}" >&2
(( verbose >= 2 )) && printf '%s: running:%s\n' "$prog" "$(printf ' %q' "${cmd[@]}")" >&2
"${cmd[@]}"
How the Optional Arguments Are Used
The key idea is that each optional argument changes the final command only when it was given. The script builds the grep command in an array (lesson 98), adding pieces conditionally:
-iis appended only when the flag was seen.-C Nis appended only whencontextis non-empty, so leaving out-cmeans "no context lines" rather than "context 0".10#turns input such as03into3.- One
-eis appended per collected pattern, so patterns with spaces or leading dashes reachgrepintact. --protects file names that start with a dash, and-is passed when no files were given, which makesgrepread standard input.
Other details:
-e?*and-c?*accept attached values (-eerror,-c1) and come before the bundling pattern, as lesson 127 explained.-ie erroris split into-iand-e, and-ethen takeserrorfrom the next argument.-?*matches only arguments of two or more characters starting with a dash, so a lone-falls through to*and is treated as a file name meaning standard input.- The verbose messages go to standard error. At level 2 the script prints the exact command it will run, quoted with
printf %qso that the boundaries between arguments are visible. - The final command runs last, so the script's exit status is
grep's: 0 when something matched, 1 when nothing matched, 2 on errors.
Running the Complete Example
The file app.log contains five lines (start, ERROR disk full, ok, warning: time out, end), and setup notes.txt contains Error in config and fine.
Without -i, the search is case-sensitive and finds nothing:
$ bash search.sh -e error app.log
$ echo $?
1
With the flag, and with a file name that contains a space:
$ bash search.sh -i -e error app.log "setup notes.txt"
app.log:2:ERROR disk full
setup notes.txt:1:Error in config
Two patterns, with -i and -e bundled:
$ bash search.sh -ie error -e "time out" app.log
app.log:2:ERROR disk full
app.log:4:warning: time out
Context lines appear only when -c is given; grep marks them with - instead of ::
$ bash search.sh -e "time out" -c 1 app.log
app.log-3-ok
app.log:4:warning: time out
app.log-5-end
The same result came from the attached form -c1 -e"time out", and -ic0 -eerror app.log printed only app.log:2:ERROR disk full.
Verbosity level 2 shows the command that was built:
$ bash search.sh -vv -i -e error -- app.log "setup notes.txt"
search.sh: 1 pattern(s), 2 file(s)
search.sh: running: grep -H -n --color=auto -i -e error -- app.log setup\ notes.txt
app.log:2:ERROR disk full
setup notes.txt:1:Error in config
With no files, the script reads standard input, and grep labels the matches accordingly:
$ printf 'one\ntwo error\n' | bash search.sh -e error
(standard input):2:two error
--color without a value forced color even though the output went to a pipe; viewing the bytes with od -c showed escape sequences such as 033 [ 3 5 m around the file name. Adding --no-color after it switched color off again, and the output was plain text.
Usage errors stop the script with status 2 before grep runs:
$ bash search.sh app.log
search.sh: at least one -e PATTERN is required
Try 'search.sh --help' for more information.
$ bash search.sh -c abc -e x app.log
search.sh: context must be a number from 0 to 999, got 'abc'
Try 'search.sh --help' for more information.
$ bash search.sh --color=sometimes -e x app.log
search.sh: invalid --color value 'sometimes'
Try 'search.sh --help' for more information.