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 ?
}
You can do:
The answers above do not work when Bash option
set -u
is enabled. Also, they are not dynamic, e.g., how to test is variable with name "dummy" is defined? Try this:Related: In Bash, how do I test if a variable is defined in "-u" mode
This is what I use every day:
This works well under Linux and Solaris down to bash 3.0.
To check for non-null/non-zero string variable, i.e. if set, use
It's the opposite of
-z
. I find myself using-n
more than-z
.You would use it like:
On a modern version of Bash (4.2 or later I think; I don't know for sure), I would try this: