values of true and false in shell
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.
[
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.