How do I know if a variable is set in bash?
For example, how to check if the user gave the 1st parameter to a function?
function a {
?? if $1 is set
}
How do I know if a variable is set in bash?
For example, how to check if the user gave the 1st parameter to a function?
function a {
?? if $1 is set
}
if [ "$1" != "" ]; then
echo \$1 is set
else
echo \$1 is not set
fi
Although for arguments it is normally best to test $#, which is the number of arguments, in my opinion.
if [ $# -gt 0 ]; then
echo \$1 is set
else
echo \$1 is not set
fi
There are many ways to do this with the following being one of them:
if [[ -z "$1" ]]
This succeeds if $1 is null, that is unset
You can do:
function a {
if [ ! -z "$1" ]; then
echo '$1 is set'
fi
}
To check for non-null (i.e.) if set, use
if [[ -n "$1" ]]
It's the opposite of "-z". I find myself using "-n" more than "-z".
To check whether a variable is set with a non-empty value, use [ -n "$x" ]
, as others have already indicated.
Most of the time, it's a good idea to treat a variable that has an empty value in the same way as a variable that is unset. But you can distinguish the two if you need to: [ -n "${x+set}" ]
("${x+set}"
expands to set
if x
is set and to the empty string if x
is unset).
To check whether a parameter has been passed, test $#
, which is the number of parameters passed to the function (or to the script, when not in a function) (see Paul's answer).