Test command in unix doesn't print an output

28,143

Solution 1

You get 0 or 1. In the exitcode.

bash-4.2$ test 4 -lt 6

bash-4.2$ echo $?
0

bash-4.2$ test 4 -gt 6

bash-4.2$ echo $?
1

Update: To store the exitcode for later use, just assign it to a variable:

bash-4.2$ test 4 -lt 6

bash-4.2$ first=$?

bash-4.2$ test 4 -gt 6

bash-4.2$ second=$?

bash-4.2$ echo "first test gave $first and the second $second"
first test gave 0 and the second 1

Solution 2

Another way is

test 4 -lt 6 && echo 1 || echo 0

But be careful in that case. If test returns success and echo 1 fails echo 0 will be executed.

Solution 3

You may type in the following command:

echo $(test -e myFile.txt) $?

Solution 4

If you want the result of a comparison on standard out instead of an exit code, you can use the expr(1) command:

$ expr 4 '<=' 6
1

Two things to note:

  1. you will likely need to quote the operator as a lot of them conflict with shell metacharacters
  2. the output value is the opposite of the return code for test. test returns 0 for true (which is the standard for exit codes), but expr prints 1 for true.
Share:
28,143
indieman
Author by

indieman

Updated on September 18, 2022

Comments

  • indieman
    indieman almost 2 years

    When I type this in the terminal

    test 4 -lt 6
    

    I don't get any output. Why not? I need that 0 or 1

    • Admin
      Admin almost 6 years
      Wouldn't it be nice if 'test' had an option to output a value immediately? Just the option. That's all we'd need.
  • indieman
    indieman over 11 years
    is there a way to pipe the exit code?
  • manatwork
    manatwork over 11 years
    No. Only output can be redirected. Anyway, usually there is no need for that. To store it for later use, just assign it to a variable. Or tell us what exactly is your intention with that value.
  • Shadur
    Shadur over 11 years
    The exit code is placed into the $? variable -- at least until it gets overwritten by the next command you execute.
  • l0b0
    l0b0 over 11 years
    PS: You can use the $PIPESTATUS array to get the result of multiple commands in a pipeline. $? will by be the result of the last command in the pipeline if the pipefail option is off (the default).
  • manatwork
    manatwork over 11 years
    3. There is a test shell builtin, which is considerably faster (about 50 times on my machine) than the test and expr executables from the coreutils package.
  • Wildcard
    Wildcard over 7 years
    @indieman, if what you need is to do something else based on the exit status, you don't even need to save it—just use if test 4 -lt 6; then echo test succeeeded; else echo test failed; fi