Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


Use the `$#` variable which contains the number of arguments.


You can use default values to avoid the nasty error. ${1:-} will expand to an empty string if your script is called without arguments.


In case it matters, michaelmior and Splognosticus's solutions are both POSIX shell compliant, so they should work anywhere. (eg, busybox, dash, tcsh, zsh)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: