Search code examples
linuxbashshellunix

Shell script - exiting script if variable is null or empty


I am expecting to use the below variable in my bash script but in case if this is empty or null what would be the best way to handle it and exit from script.

tag=$1  

I am seeing answers with 'set -u'. I know this will work but is this good for production environment?


Solution

  • There is a built-in operator for requiring that a variable is set. This will cause the script to exit if it isn't.

    tag=${1?Need a value}
    

    Commonly this is used with the : no-op near the beginning of the script.

    : ${1?Need a value}
    

    The conflation of "unset or empty" is somewhat different. There is no similar construct for exiting on an empty but set value, but you can easily use the related syntax ${var:-default} which expands to $var if it is set and nonempty, and default otherwise. There is also ${var-default} which only produces default if the variable is properly unset.

    This can be particularly useful when you want to use set -u but need to cope with a possibly unset variable:

    case ${var-} in '') echo "$0: Need a value in var" >&2; exit 1;; esac
    

    I somewhat prefer case over if [ "${var-}" = '' ], mainly because it saves me from having to wrap double quotes around ${var-}, and the pesky case of a value in $var which gets interpreted as an option to [ and gives you an error message when you least expect it. (In Bash, [[ doesn't have these problems; but I prefer to stick to POSIX shell when I can.)