views:

91

answers:

6

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
}
+4  A: 
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
Paul Creasey
The first test is backward; I think you want `[ "$1" != "" ]` (or `[ -n "$1" ]`)...
Gordon Davisson
@Gordon, fixed!
Paul Creasey
+6  A: 

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

ennuikiller
+2  A: 

You can do:

function a {
        if [ ! -z "$1" ]; then
                echo '$1 is set'
        fi
}
codaddict
Or you could do `-n` and not negate the `-z`.
Dennis Williamson
@codaddict: you need quotes around `$1`, i.e., `[ ! -z "$1" ]`. Or you can write `[[ ! -z $1 ]]` in bash/ksh/zsh.
Gilles
@Gilles: Thanks for pointing.
codaddict
+5  A: 

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".

mbrannig
+1  A: 
case "$1" in
 "") echo "blank";;
 *) echo "set"
esac
ghostdog74
A: 

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).

Gilles