Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question

3 Answers 3

up vote 7 down vote accepted

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
share|improve this answer
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

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.

share|improve this answer

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|improve this answer
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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