How to find whether or not a variable is empty in Bash
The true/false table in Test for non-zero length string in Bash: -n “$var” vs “$var”. post that @codeforester points to is absolutely fabulous in showing how you use -n and -z (their context) really matters, and that with the shell scripting languages their are any number of (seemingly subtle) gotchas to be aware of.
10 Answers 10
In Bash at least the following command tests if $var is empty:
if [[ -z "$var" ]]; then # $var is empty, do what you want fi
The command man test is your friend.
double square brackets are useless here. it may be simple [ -z «$var» ] or even easier imho if test -z «var» .. anyway +1 🙂
double square brackets are not useless, if I do not inlcude I ma getting ./test.ksh[8]: test: argument expected dunnot the reason but single bracket didn’t work but the double one had it.
Just an added comment for a specific situation not directly mentioned in the question: if the variable is unset and the set -u option has been activated, this test will fail with unbound variable . In this case, you might prefer @alexli’s solution.
@LucaBorrione Just as a late side note: «[[» can be seen as «never useless»; as using «[[» has some advantages over «[» (see stackoverflow.com/questions/669452/… for example)
var="" if [ -n "$var" ]; then echo "not empty" else echo "empty" fi
@glenn jackman: good comment; it’s true that -z is closer to what was asked. Jay has put this in his answer so I’ll refrain from updating mine and leave this up as is.
Note that -z means Zero-length string, and -n means Non-zero-length string. Reference: gnu.org/software/bash/manual/html_node/…
which is obviously very robust and shell independent.
@guettli: If $variable is empty, then the string to the left of the comparison operator becomes only x , which is then equal to the string to the right of the operator. [ x = x ] is «true», so in practice this tests whether $variable is empty or not. As an addition (3½ years after the fact 🙂 ) I would never use this myself since -z does what I probably want in a clearer way, but I wanted to add this answer since this method is frequently seen «in the wild»; perhaps written this way on purpose by people who have had different experiences than I have.
«Since this method is frequently seen «in the wild»;» This is commonly seen in configure scripts, and it works with sh and any non-standard bash which might not have the -z flag. This situation was commonly the case when there were many flavors of Unix which were all mildly incompatible with each other in minor details, such as support for a -z flag. Now that Linux has taken over, it is not much of an issue (unless you are on an old, funny Unix)
prints yes if the variable is set. $ will return 1 when the variable is set, otherwise it will return empty string.
While not mentioned in the question, an important advantage of this answer is that it works even when the variable is undefined and the set -u option ( nounset ) is activated. Almost all other answers to this question will fail with unbound variable in this case.
This :+ notation is also useful for situations where you have optional command line parameters that you have specified with optional variables. myprogram $ $
This is a quick way to check the validity of an entry of a variable and exit if not set: [ «$variable» ] || exit
The question asks how to check if a variable is an empty string and the best answers are already given for that.
But I landed here after a period passed programming in PHP, and I was actually searching for a check like the empty function in PHP working in a Bash shell.
After reading the answers I realized I was not thinking properly in Bash, but anyhow in that moment a function like empty in PHP would have been soooo handy in my Bash code.
As I think this can happen to others, I decided to convert the PHP empty function in Bash.
a variable is considered empty if it doesn’t exist or if its value is one of the following:
- «» (an empty string)
- 0 (0 as an integer)
- 0.0 (0 as a float)
- «0» (0 as a string)
- an empty array
- a variable declared, but without a value
Of course the null and false cases cannot be converted in bash, so they are omitted.
function empty < local var="$1" # Return true if: # 1. var is a null string ("" as empty string) # 2. a non set variable is passed # 3. a declared variable or array but without a value is passed # 4. an empty array is passed if test -z "$var" then [[ $( echo "1" ) ]] return # Return true if var is zero (0 as an integer or "0" as a string) elif [ "$var" == 0 2>/dev/null ] then [[ $( echo "1" ) ]] return # Return true if var is 0.0 (0 as a float) elif [ "$var" == 0.0 2> /dev/null ] then [[ $( echo "1" ) ]] return fi [[ $( echo "" ) ]] >
if empty "$" then echo "empty" else echo "not empty" fi
Demo:
The following snippet:
#!/bin/bash vars=( "" 0 0.0 "0" 1 "string" " " ) for (( i=0; i; i++ )) do var="$" if empty "$" then what="empty" else what="not empty" fi echo "VAR \"$var\" is $what" done exit
VAR "" is empty VAR "0" is empty VAR "0.0" is empty VAR "0" is empty VAR "1" is not empty VAR "string" is not empty VAR " " is not empty
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.
Shell script — exiting script if variable is null or empty
I am expecting to use the below variable in my bash script but in case if this is empty or null what would be the best way to handle it and exit from script.
I am seeing answers with ‘set -u’. I know this will work but is this good for production environment?
yes, variable consisting of whitespaces, considered empty. basically, I am thinking to put a check like if [[ ! -z «$
7 Answers 7
There is a built-in operator for requiring that a variable is set. This will cause the script to exit if it isn’t.
Commonly this is used with the : no-op near the beginning of the script.
The conflation of «unset or empty» is somewhat different. There is no similar construct for exiting on an empty but set value, but you can easily use the related syntax $ which expands to $var if it is set and nonempty, and default otherwise. There is also $ which only produces default if the variable is properly unset.
This can be particularly useful when you want to use set -u but need to cope with a possibly unset variable:
case $ in '') echo "$0: Need a value in var" >&2; exit 1;; esac
I somewhat prefer case over if [ «$» = » ] , mainly because it saves me from having to wrap double quotes around $ , and the pesky case of a value in $var which gets interpreted as an option to [ and gives you an error message when you least expect it. (In Bash, [[ doesn’t have these problems; but I prefer to stick to POSIX shell when I can.)
How to determine if a bash variable is empty?
What is the best way to determine if a variable in bash is empty («»)? I have heard that it is recommended that I do if [ «x$variable» = «x» ] Is that the correct way? (there must be something more straightforward)
In Bash, [[ -v VAR]] is to check if VAR is defined, [[ -z $VAR ]] is to check if «$VAR» is expanded to null string ( «» ). Thus, you can use [[ -v VAR && -z $VAR ]] . read more here (with official reference)
15 Answers 15
This will return true if a variable is unset or set to the empty string («»).
The double quotes ensure that the variable doesn’t get split. A simple $var on a command line will be split by its whitespace into a list of parameters, while «$var» will always be only one parameter. Quoting variables often is a good practice and stops you from tripping up on filenames containing whitespace (among other things). Example: after doing a=»x —help» , try cat $a — it will give you the help page for cat . Then try cat «$a» — it will (usually) say cat: x —help: No such file or directory . In short, quote early and quote often and you will almost never regret it.
I feel like your answer requires a caveat — namely if your bash script has something like set -u then the answer will break/fail at that point. There is a subtle (and usually ignored) difference between unset and empty . Note that the distinction is only really important if it’s important to you, or if the script has already set -u .
In Bash, when you’re not concerned with portability to shells that don’t support it, you should always use the double-bracket syntax:
if [[ -z $variable ]] if [[ -z "$variable" ]] if [[ ! $variable ]] if [[ ! "$variable" ]]
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 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):
If you want to know whether a variable is null but not unset:
@AlastairIrvine: I mention portability in the first sentence of my answer, the question title and body contain the word «Bash» and the question is tagged bash, and the double bracket structure provides clear advantages in many ways. And I don’t recommend mixing bracket styles for reasons of consistency and maintainability. If you need maximum, lowest common denominator portability, use sh instead of Bash. If you need the increased capabilities that it provides, use Bash and use it fully.
@BrunoBronosky: I reverted the edit. There’s no requirement for ; at the end. The then can be on the next line without a semicolon at all.
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:
if [ -z "$" ]; then echo "VAR is unset or set to the empty string" fi if [ -z "$" ]; then echo "VAR is unset" fi if [ -z "$" ]; then echo "VAR is set to the empty string" fi if [ -n "$" ]; then echo "VAR is set to a non-empty string" fi if [ -n "$" ]; then echo "VAR is set, possibly to the empty string" fi if [ -n "$" ]; then echo "VAR is either unset or set to a non-empty string" fi
Here is the same thing but in handy table form:
+-------+-------+-----------+ VAR is: | unset | empty | non-empty | +-----------------------+-------+-------+-----------+ | [ -z "$" ] | true | true | false | | [ -z "$" ] | true | false | false | | [ -z "$" ] | false | true | false | | [ -n "$" ] | false | false | true | | [ -n "$" ] | false | true | true | | [ -n "$" ] | true | false | true | +-----------------------+-------+-------+-----------+
The $ construct expands to the empty string if VAR is unset or to foo if VAR is set to anything (including the empty string).
The $ construct expands to the value of VAR if set (including set to the empty string) and foo if unset. This is useful for providing user-overridable defaults (e.g., $ says to use red unless the variable COLOR has been set to something).
The reason why [ x»$» = x ] is often recommended for testing whether a variable is either unset or set to the empty string is because some implementations of the [ command (also known as test ) are buggy. If VAR is set to something like -n , then some implementations will do the wrong thing when given [ «$» = «» ] because the first argument to [ is erroneously interpreted as the -n operator, not a string.