How do I know if a variable is set in Bash?
For example, how do I check if the user gave the first parameter to a function?
function a {
# if $1 is set ?
}
How do I know if a variable is set in Bash?
For example, how do I check if the user gave the first parameter to a function?
function a {
# if $1 is set ?
}
I always use this one, based on the fact that it seems easy to be understood by anybody who sees the code for the very first time:
And, if wanting to check if not empty;
That's it.
Here's how to test whether a parameter is unset, or empty ("Null") or set with a value:
Source: POSIX: Parameter Expansion:
If you wish to test that a variable is bound or unbound, this works well, even after you've turned on the nounset option:
(Usually) The right way
where
${var+x}
is a parameter expansion which evaluates to nothing ifvar
is unset, and substitutes the stringx
otherwise.Quotes Digression
Quotes can be omitted (so we can say
${var+x}
instead of"${var+x}"
) because this syntax & usage guarantees this will only expand to something that does not require quotes (since it either expands tox
(which contains no word breaks so it needs no quotes), or to nothing (which results in[ -z ]
, which conveniently evaluates to the same value (true) that[ -z "" ]
does as well)).However, while quotes can be safely omitted, and it was not immediately obvious to all (it wasn't even apparent to the first author of this quotes explanation who is also a major Bash coder), it would sometimes be better to write the solution with quotes as
[ -z "${var+x}" ]
, at the very small possible cost of an O(1) speed penalty. The first author also added this as a comment next to the code using this solution giving the URL to this answer, which now also includes the explanation for why the quotes can be safely omitted.(Often) The wrong way
This is often wrong because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if
var=''
, then the above solution will output "var is blank".The distinction between unset and "set to the empty string" is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.
The distinction may not be essential in every scenario though. In those cases
[ -z "$var" ]
will be just fine.Although for arguments it is normally best to test $#, which is the number of arguments, in my opinion.