3 ms·
When using `set -eu`, how do you check the number of arguments?: if [ -z "$1" ]; then usage(); exit 1; fi; If I'm using `set -eu`, that di
by pjungwir 12y ago
When using `set -eu`, how do you check the number of arguments?:
if [ -z "$1" ]; then
usage();
exit 1;
fi;
If I'm using `set -eu`, that dies on the `$1` with a nasty error message, rather than printing my usage message. I've resorted to moving `set -eu` to after these kind of checks, but that makes me uneasy.
- michaelmior 12y agoUse the `$#` variable which contains the number of arguments.
- Splognosticus 12y agoYou can use default values to avoid the nasty error. ${1:-} will expand to an empty string if your script is called without arguments.
- scott_karana 12y agoIn case it matters, michaelmior and Splognosticus's solutions are both POSIX shell compliant, so they should work anywhere. (eg, busybox, dash, tcsh, zsh)