what is -z option in test command(linux)

In one of my lab tutorial there was a command to be checked.

test -z $LOGNAME || echo Logname is not defined

when I execute this command the output is "Logname is not defined". Man page for test says

> -z STRING
> the length of STRING is zero

when I echo $LOGNAME it prints out my login name. So there is a value for $LOGNAME. In the first command above since the right part of the command is executed, it implies the left part has returned false. Why does it return false when $LOGNAME has a value?

2

2 Answers

The line

test -z $LOGNAME || echo Logname is not defined

is an OR list, and can be translated as:

DO echo Logname is not defined IF test -z $LOGNAME FAILS

As you mention in your question, test -z $LOGNAME tests whether $LOGNAME is zero length ... and since it isn't, the test fails. Replacing || with && as follows will give you the behaviour you want:

test -z $LOGNAME && echo Logname is not defined

EDIT: As per William Pursell's comment below, test -n (test for a non-zero-length string) and || might make more conceptual sense, but you need to quote $LOGNAME in this case (and in fact it's a good idea to get into the habit of quoting variables in general):

test -n "$LOGNAME" || echo Logname is not defined
5

test command looks for mentioned file in current folder, If you want check file from another location provide with full path and don't use -z option or use -s option . You can do as below:

test /usr/bin/logname && echo $LOGNAME || echo Logname is not defined

or

test -s /usr/bin/logname && echo $LOGNAME || echo Logname is not define

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like