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)
feedback
|
|
This will return true if a variable is unset.
| |||||
|
feedback
|
|
If you're interested in distinguishing the cases of set-empty versus unset status, look at the -u option for bash:
| |||
|
feedback
|
|
Another options I've used is to set a variable, but it can be overridden by another variable eg
If the | ||||
feedback
|
|
An alternate I've seen to
Anyway if you're disallowing unset variables (either by
Note: this will leave your variable undef. | |||
feedback
|
|
the entire if-then and -z are unnecessary. [ "$foo" ] && echo "foo is not empty" [ "$foo" ] || echo "foo is indeed empty" | |||||||||
feedback
|
|
This is true exactly when $FOO is set and empty:
| |||
|
feedback
|
|
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:
| ||||
|
feedback
|
|
Personally prefer more clear way to check :
| |||||||
feedback
|
|
The following is an example of how you can distinguish unset from set to the empty string, and it works in any POSIX-compatible shell:
The The reason why | |||
|
feedback
|