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

You can ignore the automatic exit due to set -u by setting a default value in the parameter expansion:

#!/bin/sh
set -u
if [ -z "${1-}" ] ; then
    echo "\$1 not set or empty"
    exit 1
fi
echo "$2"    # this will crash if $2 is unset

The syntax is ${parameter-default}, which gives the string default if the named parameter is unset, and the value of parameter otherwise. Similarly, ${parameter:-default} gives default if the named parameter is unset or empty. Above, we just used an empty default value. (${1:-} would be the same here, since we'd just change an empty value to an empty value.)

That's a feature of the POSIX shell and works with other variables too, not just the positional parameters.

If you want to tell the difference between an unset variable and an empty value, use ${par+x}:

if [ "${1+x}" != x ] ; then
    echo "\$1 is not set"
fi

$# 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;

My personal favorite :

if
  (($#))
then
  # We have at least one argument
fi

Or :

if
  ((!$#))
then
  # We have no argument
fi

Tags:

Bash