The test
command on Unix-like systems provides two special syntax forms for checking whether a string is empty or not:
test -z "$foo" # the length of $foo is zero
test -n "$foo" # the length of $foo is nonzero
These forms are actually redundant, and equivalent to the following:
test "$foo" = ""
test "$foo" != ""
Why are there two different forms? Is there a historical reason or justification for this design decision?
Background, as far as I know it. Bash descends from an older shell Almquist shell. The Almquist shell didn't internalize expressions. So you wrote them with using a utility called test which just resolved them to a return code,
if test "$foo" = ""; then echo "Foo has a length of 0"; fi;
That would call the actually utility /bin/test
and test that first argument $foo
was equal to third argument ( an empty string).
It also provided another option,
if test -z "$foo"; then echo "Foo has a length of 0"; fi;
I don't understand why this syntax exists though.
/bin/test
utility exists to this day. The shell (particularlybash
) builtin with that name (as several others) is just for performance reasons.