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

  • 1
    Wouldn't it be nice if 'test' had an option to output a value immediately? Just the option. That's all we'd need. – Todd Walton Sep 6 '18 at 13:48

You get 0 or 1. In the exitcode.

bash-4.2$ test 4 -lt 6

bash-4.2$ echo $?

bash-4.2$ test 4 -gt 6

bash-4.2$ echo $?

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
  • 1
    is there a way to pipe the exit code? – indieman Oct 11 '12 at 7:38
  • 3
    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. – manatwork Oct 11 '12 at 7:41
  • 2
    The exit code is placed into the $? variable -- at least until it gets overwritten by the next command you execute. – Shadur Oct 11 '12 at 7:45
  • 1
    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). – l0b0 Oct 11 '12 at 9:26
  • @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 – Wildcard Oct 27 '16 at 18:57

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.


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

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.
  • 1
    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. – manatwork Oct 11 '12 at 11:18
  • +1 for the second point. Could get a bug that is very frustrating to find if you mess that up. – Emanuel Berg Oct 11 '12 at 17:18

You may type in the following command:

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.