what does the -z flag mean here

What does the -z flag mean in the code below:

if [ -z $TEST_PARAM ]; then

And is there a list of such flags?

For a flag like ls -l, I know where to find it, but for a single flag, I didn’t get any website describes it.

Asked By: betteroutthanin


-z STRING means:

the length of STRING is zero

You can see a list of all of these with man test.

[ is an alias for the test command, although usually implemented by your shell in practice. You probably have a /bin/[, though. All of these -X tests are options to test.

Answered By: Michael Homer

[ is another name for the test utility. The only difference between them is that [ expects an extra ] parameter at the end. Most systems have a [ man page with the same content as the test man page.

Most shells have [ and test built in, so the exact capabilities described in the man page may differ slightly from those actually available in the shell. -z is a standard feature available in all implementations though. Look for the description of the test builtin or the section on conditional expressions to find operators like -z.

The command [ -z $TEST_PARAM ] should actually be [ -z "$TEST_PARAM" ], because variable expansions outside double quotes do far more than expand variables. See Why does my shell script choke on whitespace or other special characters? for more details. Without quotes, the value of TEST_PARAM is split into words which are expanded as glob patterns. In contrast, "$TEST_PARAM" expands to the value of the TEST_PARAM variable. If the value of TEST_PARAM is empty, then $TEST_PARAM is expanded into a list of zero words, so the command that is executed is [ -z ]. With only a single word to express the conditional expression, the conditional is true if this word is non-empty. Here -z is not an operator but some non-empty string.

See also using single or double bracket – bash

It means “if the parameter doesn’t exist, do the following”.

You can see this with:

$ ABC='1'                                                                                     
$ if [ -z $ABC ]; then echo "ABC"; # Nothing
$ if [ -z $XYZ ]; then echo "yes"; # echo "Yes"

One example of where I use this, is in my .bashrc file to invoke tmux, but not recursively, as in:

[ -z $TMUX ] && export TERM=xterm-256color && exec tmux
Answered By: Michael Durrant
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.