In one of my lab tutorial there was a command to be checked.
test -z $LOGNAME || echo Logname is not definedwhen I execute this command the output is "Logname is not defined". Man page for test says
> -z STRING
> the length of STRING is zerowhen 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?
22 Answers
The line
test -z $LOGNAME || echo Logname is not definedis 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 definedEDIT: 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
3test -s /usr/bin/logname && echo $LOGNAME || echo Logname is not define