I'm trying to improve this nasty old script. I found an undefined variable error to fix, so I added set -u
to catch any similar errors.
I get an undefined variable error for "$1", because of this code
if [ -z "$1" ]; then
process "$command"
It just wants to know if there are arguments or not. (The behaviour when passed an empty string as the first argument is not intended. It won't be a problem if we happen to fix that as well).
What's a good way to check whether we have arguments, when running with set -u
?
The code above won't work if we replace "$1" with "$@", because of the special way "$@" is expanded when there is more than one argument.
$#
contains the number of arguments, so you can test for $1
, $2
, etc. to exist before accessing them.
if (( $# == 0 )); then
# no arguments
else
# have arguments
fi;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With