Testing Against The Null String

The null string is an exceptional and sometimes problematic value.

Consider the following code:

 if [ $a = "" ]; then echo "null string"; fi
If $a is indeed the null string, the Shell won't be able to recognize and interpret the command, since test will be called with syntactically invalid arguments. The command would appear to the shell like this if $a were the null string:
 if [ = "" ]; then echo "null string"; fi
We can fix this with quotes:
 if [ "$a" = "" ]; then echo "null string"; fi
but if the contents of the string $a is unconstrained, and it contains something like != or -a or some other option to the test operator, it will cause the shell to issue a syntax error, and not perform the evaluation the programmer desired.

Therefore:

Use double aliasing to test values:

 if [ "x$a" = x ]; then echo "null string"; fi
 if [ "x$a" = xBamboozled ]; then echo "Bamboozled"; fi
 case x$a in
xwpasskey) ... ;;
x) ... handle null string;;
 esac
(Yes, you need both the prefixed x and the double quotes. If the double quotes are omitted, you'll get a wrong result if the string $a equals, for instance, ' = x -o x'.)

Security Note:

This type of care is especially important when writing shell scripts that are intended to be executed SetUID, or to be executed by a networking daemon, or CGI script, as a hostile user can obtain unintended privileges through crafty probes into carelessly-written shell scripts.


Isn't there a difference between empty string and null string? in databases on the market today, a null field does not mean the same thing as empty string... This page looks like you're dealing with empty strings ("" != null).

I presume you mean "database management systems" aka DBMSs, not "databases". "Databases on the market today" are collections of data, not software. In most DBMS software, null and empty string are not equivalent. The above appears to refer to a UNIX or similar shell scripting language.


See also: JavaScriptSucks (null, NAN, etc. complaints)


CategoryUnixShellPattern CategoryNull


EditText of this page (last edited April 20, 2012) or FindPage with title or text search