If I want to check for the null string I would do
[ -z $mystr ]
but what if I want to check whether the variable has been defined at all? Or is there no distinction in bash scripting?
If I want to check for the null string I would do
[ -z $mystr ]
but what if I want to check whether the variable has been defined at all? Or is there no distinction in bash scripting?
another option: the "list array indices" expansion:
the only time this expands to the empty string is when
foo
is unset, so you can check it with the string conditional:should be available in any bash version >= 3.0
https://stackoverflow.com/a/9824943/14731 contains a better answer (one that is more readable and works with
set -o nounset
enabled). It works roughly like this:not to shed this bike even further, but wanted to add
is something you could add to the top of a script, which will error if variables aren't declared anywhere in the script. The message you'd see is
unbound variable
, but as others mention it won't catch an empty string or null value. To make sure any individual value isn't empty, we can test a variable as it's expanded with${mystr:?}
, also known as dollar sign expansion, which would error withparameter null or not set
.call set without any arguments.. it outputs all the vars defined..
the last ones on the list would be the ones defined in your script..
so you could pipe its output to something that could figure out what things are defined and whats not
Advanced bash scripting guide, 10.2. Parameter Substitution:
to base your program logic on whether the variable $mystr is defined or not, you can do the following:
now, if isdefined=0 then the variable was undefined, if isdefined=1 the variable was defined
This way of checking variables is better than the above answer because it is more elegant, readable, and if your bash shell was configured to error on the use of undefined variables
(set -u)
, the script will terminate prematurely.Other useful stuff:
to have a default value of 7 assigned to $mystr if it was undefined, and leave it intact otherwise:
to print an error message and exit the function if the variable is undefined:
Beware here that I used ':' so as not to have the contents of $mystr executed as a command in case it is defined.