shell - How to check if a variable is set in Bash? -
how know if variable set in bash?
for example, how check if user gave first parameter function?
function { # if $1 set ? }
the right way
if [ -z ${var+x} ]; echo "var unset"; else echo "var set '$var'"; fi where ${var+x} parameter expansion evaluates nothing if var unset, , substitutes string x otherwise.
quotes digression
quotes can omitted (so can ${var+x} instead of "${var+x}") because syntax & usage guarantees expand not require quotes (since either expands x (which contains no word breaks needs no quotes), or nothing (which results in [ -z ], conveniently evaluates same value (true) [ -z "" ] well)).
however, while quotes can safely omitted, , not obvious (it wasn't apparent the first author of quotes explanation major bash coder), better write solution quotes [ -z "${var+x}" ], @ small possible cost of o(1) speed penalty. first author added comment next code using solution giving url answer, includes explanation why quotes can safely omitted.
the wrong way
if [ -z "$var" ]; echo "var unset"; else echo "var set '$var'"; fi this because doesn't distinguish between variable unset , variable set empty string. say, if var='', above solution incorrectly output var unset.
but distinction essential in situations user has specify extension, or additional list of properties, , not specifying them defaults non-empty value, whereas specifying empty string should make script use empty extension or list of additional properties.
Comments
Post a Comment