I read that in shell, true command returns 0 => logical true. false command return 1 => logical false. But I get surprising results when i run.
if [ 0 ]
then
echo "0 is true."
else
echo "0 is false."
fi
if [ 1 ]
then
echo "1 is true."
else
echo "1 is false."
fi
if [ false ]
then
echo "false is true."
else
echo "false is false."
fi
if [ true ]
then
echo "true is true."
else
echo "true is false."
fi
I get these results.
0 is true. 1 is true. false is true. true is true.
[
is a command. If passed a non-zero-length string it returns true. If you want to run the true
or false
commands then don't run the [
command instead.
The test if [ 0 ]
tests whether 0
is the empty string (it isn't) and returns true if it is not empty. The test if [ 1 ]
similarly tests whether 1
is the empty string and returns true if it is not empty. Likewise, the other two tests check whether the strings true
and false
are empty...
If you want to test the commands, execute the commands:
if false; then echo False is true; else echo False is false; fi
if true ; then echo True is true; else echo True is false; fi
Most machines don't have commands called 0
or 1
, so you can't readily invoke them as commands.
You could also experiment with:
if sh -c "exit 1"; then echo Shell exited as true; else echo Shell exited as false; fi
if sh -c "exit 0"; then echo Shell exited as true; else echo Shell exited as false; fi
In 7th Edition Unix, /bin/test
(or possibly /usr/bin/test
) was the test program, but you would normally find a link /bin/[
. When it was invoked by the name [
, it demanded that its last argument was ]
, so you could write a square bracketed condition. (Macs with macOS 10.14.6 Mojave still have /bin/[
— it still works. Linux systems usually have /usr/bin/[
, and it still works too.)
Shortly after that, the test
operation was built into the shell, instead of being a separate executable, but the semantics remained largely unchanged. Because they are now different (built-in vs the executable), sometimes the test operations have different functionality. POSIX defines a baseline; various shells and systems provide various extensions.
To this day, the autoconf
suite recommends the use of test
over [
, though that is primarily because it uses square brackets for another purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With