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?
Check if String is Empty using -z String Operator -z string operator checks if given string operand's size is zero. If the string operand is of zero length, then it returns true, or else it returns false. The expression to check if string is empty is [ -z "$s" ] where s is string. String is empty.
Here is what I think is a much clearer way to check if a variable is defined: var_defined() { local var_name=$1 set | grep "^${var_name}=" 1>/dev/null return $? }
$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With