Looking for the correct syntax that looks at a bash variable and determines if its null, if it is then do ... otherwise continue on.
Perhaps something like if [ $lastUpdated = null?; then... else...
Just test if the variable is empty:
if [ -z "$lastUpdated" ]; then
# not set
fi
FOO= (no value give) is equivalent to FOO="", which sets the value of FOO to the empty string. The various parameter expansions (${FOO:-default} vs ${FOO-default}, as an example) allow you to make this distinction. A quoted expansion of an unset variable, such as you use, expands to the empty string, so -z can not distinguish the two states.Expanding on @chepner's comments, here's how you could test for an unset (as opposed to set to a possibly empty value) variable:
if [ -z "${lastUpdated+set}" ]; then
The ${variable+word} syntax gives an empty string if $variable is unset, and the string "word" if it's set:
$ fullvar=somestring
$ emptyvar=
$ echo "<${fullvar+set}>"
<set>
$ echo "<${emptyvar+set}>"
<set>
$ echo "<${unsetvar+set}>"
<>
[ -z ] does and why) mans it's much easier to use double-quotes. To put it another way: if someone thinks [ -z ${lastUpdated+set} ] is a good way to test for a set variable, they're likely to infer that [ -n ${lastUpdated+set} ] is a good way to test for an unset variable, but it will completely fail.To sum it all up: There is no real null value in bash. Chepner's comment is on point:
The bash documentation uses null as a synonym for the empty string.
Therefore, checking for null would mean checking for an empty string:
if [ "${lastUpdated}" = "" ]; then
# $lastUpdated is an empty string
fi
If what you really want to do is check for an unset or empty (i.e. "", i.e. 'null') variable, use trojanfoe's approach:
if [ -z "$lastUpdated" ]; then
# $lastUpdated could be "" or not set at all
fi
If you want to check weather the variable is unset, but are fine with empty strings, Gordon Davisson's answer is the way to go:
if [ -z ${lastUpdated+set} ]; then
# $lastUpdated is not set
fi
(Parameter Expansion is what's going here)
If you're looking to use something similar to JavaScript's inline || (OR) operator for using the first "truthy" value i.e. return myVar || "default value", there's a bash way to do that using a - (minus/hyphen) operator. However note that unlike JS, "" (empty string) on the first value will be returned unless you add a :.
DEFAULT="blue"
echo ${CUSTOMER_INPUT-$DEFAULT} # Output: "blue"
# Note that $ is not required as it is implied on CUSTOMER_INPUT
CUSTOMER_INPUT="red"
echo ${CUSTOMER_INPUT-$DEFAULT} # Output: "red"
CUSTOMER_INPUT=""
echo ${CUSTOMER_INPUT-$DEFAULT} # Output: ""
echo ${CUSTOMER_INPUT:-$DEFAULT} # Output: "blue"
bashdocumentation usesnullas a synonym for the empty string.