Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

What is the difference between

if [ -z "$1" ] 


if [ "$1" = "" ] 

or are they the same?

I have found my self writing the second one in some scripts, but then I read here that the -z flag is does the same.

If there are some problems using the second one, should we ignore that the first one looks a little better?

share|improve this question
For a detailed comparison, see my answer on Stack Overflow. Also, see this and this. – Dennis Williamson Nov 7 '10 at 22:25
nice links, with some nice answers :) – Johan Nov 8 '10 at 4:27
up vote 23 down vote accepted

[ "$1" = "" ] and [ -z "$1" ] are exactly equivalent in bash and other POSIX-compliant shells. (Note that there must be a space on each side of the brackets, unless there is a non-word-constituent character like ;.)

[ is a shell built-in like any other; in fact it can also be spelled test (the only difference between the two is that [ requires a ] as the last argument). So if you run [ "$1" = "" ] with $1 expanding to -z, the test operator sees three arguments: -z, = and the empty string. Some older Bourne shells sometimes threw parse errors when an operand looked like an operator in this way, even if there was no ambiguity in the complete expression. I don't know if any version did in fact have trouble with this particular expression, but more complex expressions could throw them off. There may also have been versions that had trouble with empty words; these would not have supported [ -z "$1" ] either. A common shell idiom is [ x"$1" = x"" ]. It avoids any risk of having operands parsed as operators because no operator starts with a letter.

In ksh, bash and zsh, you can use the double bracket syntax, [[ -z $1 ]]. This newer syntax (it's from the late 1980s rather than the mid-1970s) eliminates the risk of having operands parsed as operators by using a special syntactic construct rather than an ordinary built-in. Operators must appear literally, unquoted within the double brackets, and you don't need to double quote variable expansions.

share|improve this answer
Fixed the typo with the missing space next to the bracket. – Johan Nov 7 '10 at 17:24

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.