0

How can I echo the value of [ 5 -gt 4 ] ,that is a test expression in bash?

[ 5 -gt 4 ] | echo

and

echo `[ 5 -gt 4 ]`

both end up printing a blank line

@Thomas Dickey 's answer works but could some one explain why the above two don`t work?

4

Your commands don't work the way you expect them to because the test does not output anything to its standard output stream. It's the standard output stream that gets piped to the next command in a pipeline (your first command), and it's the standard output that replaces a command substitution (your second command).

As an aside, note that even if the left hand side of your first pipeline produced something on its standard output stream, echo on the right would not display it. The echo utility does not read from its standard input (but e.g. cat does).


Any shell command returns an exit status. This exit status is what e.g. an if statement acts upon. The exit status is never outputted to e.g. the terminal or it would interfere with the actual output of the command or script.

When you use

[ 3 -gt 4 ]

you call the [ utility with some arguments. That utility returns an exit status. It is exactly equivalent to

test 3 -gt 4

See man test and man [ (or help test in the bash shell).

The exit status of the most recently executed command is stored in the special variable $?.

You may save this in an ordinary variable, or output it to the terminal:

[ 3 -gt 4 ]
printf 'Exit status of test was %s\n' "$?"
printf 'Exit status of printf was %s\n' "$?"

Note that printf also produces its own exit status, so if the printf call went ok, the value $? would be zero after outputting the status of the test.

The code above would likely output

Exit status of test was 1
Exit status of printf was 0

Note that the test itself never outputs anything here. It just provides an exit status.

  • Thanks a lot for the concise explanation! – strider0160 Mar 24 at 12:04
0

Just this:

[ 5 -gt 4 ]
echo $?
  • But why doesn`t the other method work? – strider0160 Mar 24 at 11:01
  • @strider0160 because [ doesn't produce any output, it just sets a status/return code. – nohillside Mar 24 at 11:11
  • why cant that be printed? How does an if statement interpret the test then ? I am a beginner at bash forgive me if these questions are too basic! – strider0160 Mar 24 at 11:14
  • 1
    @strider0160 Output means text that would be sent to the terminal (unless redirected or used in some other way). A test does not by itself produce any output. All commands return an exit status. This is never printed to the terminal, but what Thomas is showing is how to print the value of the special $? variable which holds the exit-status of the most recently executed command (the test in this case). – Kusalananda Mar 24 at 11:20

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.