• Uncategorized

About bash : test-command-in-unix-doesnt-print-output

Question Detail

Why is there no output to the command test 3 -lt 6 in the unix terminal? Shouldn’t test output a 0 or a 1?

I did a man test and it says

Exit with the status determined by EXPRESSION

Question Answer

The exit status is not printed, it is just returned. You can test it in if or while, for example

if test 3 -lt 6 ; then
    echo ok
    echo not ok

Moreover, the exit code of the last expression is kept in $?:

test 3 -lt 6; echo $?

test returns an exit status, which is the one that indicates if the test was succesfull. You can get it by reading $? right after executing test or you can use it directly in a control structure, for example:

if test 3 -lt 6 
  do echo "everything is aaaaalright"
  else echo "whaaat?"

Every command in the shell has a return value, not just test. Return values are rairly printed, we test them directly, for example with an if or while statement, or maybe use it in a shortcut with && or ||. Sometimes we might store the return value, which is also available in the variable ?.

The test command is rather ancient. Since you have tagged bash then you might wish to consider using

if (( 3 < 6 )); then 

for arithmetic tests, or

if [[ $name == "Fred Bloggs" ]] ; then 

for textual or pattern tests.

These are generally more intuitive and less error prone. Like test, (( )) and [[ ]] are commands in their own right, and can be used without if or while. They return 0 (success) on true, and 1 (failure) on false.

By the way, when you do a man test you are actually looking at the doc for the test program. You might be better using man bash or help test.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.