Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`set -u` (nounset) vs checking whether I have arguments

Tags:

bash

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.

like image 785
sourcejedi Avatar asked Apr 30 '17 14:04

sourcejedi


1 Answers

$# 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;
like image 137
Siguza Avatar answered Sep 28 '22 10:09

Siguza