Bash Strict Mode is defined as follows:
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
http://redsymbol.net/articles/unofficial-bash-strict-mode/
Consider the following parsing of positional parameters in a Bash script:
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
usage() {
echo ""
echo "usage:"
echo "$0 [options]"
echo " -r | --redirect-uri: redirect uri"
echo " -a | --app-role: app role id"
echo " -h | --help: help"
echo ""
}
redirect_uri=""
app_role=""
while [ "$1" != "" ]; do
case $1 in
-r | --redirect-uri)
shift
redirect_uri="$1"
;;
-a | --app-role)
shift
app_role="$1"
;;
-h | --help)
usage
exit 0
;;
*)
usage
exit 1
;;
esac
shift
done
...
This doesn't work with the following error, e.g.:
$ ./app.sh -r https://example.net:8080/auth/callback -a 53b37b21-2c6e-4731-a5e5-15b98052c686
./app.sh: line 18: $1: unbound variable
I think the reason is the final check in the while
condition, after shift
, where $1
is undefined.
How can I terminate parameter parsing in the while
statement without causing the script to crash, when using Bash Strict Mode?
set -o errexit -o nounset -o pipefail
? (btw, there's nothing bash-specific in those). – Stéphane Chazelas Apr 04 '23 at 09:43set -u
can be useful at least as a development helper, I'd be really wary of things likeset -e
esp. in connection withpipefail
. If you ever use pipelines, I'd wager that will cause your script to mysteriously fail without you having any idea why it happens. – ilkkachu Apr 04 '23 at 12:54