How can I echo the value of [ 5 -gt 4 ] ,that is a test expression in bash?
[ 5 -gt 4 ] | echo
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?
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.
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
man test and
man [ (or
help test in the
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' "$?"
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.
[ 5 -gt 4 ] echo $?