What is the best way to determine if a variable in bash contains ""?
I have heard it recommended that I do if [ "x$variable" = "x" ]
Is that the correct way? (there must be something more straightforward)
|
|
This will return true if a variable is unset.
|
|||||||||||||
|
|
In Bash, when you're not concerned with portability to shells that don't support it, you should always use the double-bracket syntax: Any of the following:
In Bash, using double square brackets, the quotes aren't necessary. You can simplify the test for a variable that does contain a value to:
This syntax is compatible with zsh and ksh (at least ksh93, anyway). It does not work in pure POSIX or older Bourne shells such as sh or dash. See my answer here and BashFAQ/031 for more information about the differences between double and single square brackets. You can test to see if a variable is specifically unset (as distinct from an empty string):
where the "x" is arbitrary. If you want to know whether a variable is null but not unset:
|
|||||||
|
|
If you're interested in distinguishing the cases of set-empty versus unset status, look at the -u option for bash:
|
|||
|
|
|
Another options I've used is to set a variable, but it can be overridden by another variable eg
If the |
||||
|
|
A variable in bash (and any POSIX-compatible shell) can be in one of three states:
Most of the time you only need to know if a variable is set to a non-empty string, but occasionally it's important to distinguish between unset and set to the empty string. The following are examples of how you can test the various possibilities, and it works in bash or any POSIX-compatible shell:
The The The reason why |
|||||
|
|
An alternate I've seen to
Anyway if you're disallowing unset variables (either by
Note: this will leave your variable undef. |
|||
|
|
the entire if-then and -z are unnecessary. [ "$foo" ] && echo "foo is not empty" [ "$foo" ] || echo "foo is indeed empty" |
|||
|
This is true exactly when $FOO is set and empty:
|
|||
|
|
|
Personally prefer more clear way to check :
|
|||||||||||||||
|
|
The question asks how to check if a variable is an empty string and the best answers are already given for that.
Of course the null and false cases cannot be converted in bash, so they are omitted.
outputs:
Having said that in a bash logic the checks on zero in this function can cause side problems imho, anyone using this function should evaluate this risk and maybe decide to cut those checks off leaving only the first one. |
||||
|
|
|
oneliner extension of duffbeer703's solution:
|
|||
|
|