A quick note: square braces are actually a Unix command. See if your system has a file named /bin/[
or /usr/bin/[
. Actually try the following:
$ ls i-il /bin[ /bin/test 571541 -r-xr-xr-x 2 root wheel 43120 Aug 17 2011 /bin/[ 571541 -r-xr-xr-x 2 root wheel 43120 Aug 17 2011 /bin/test
This first number is the i-node number. You see that /bin/[
and /bin/test
tightly coupled to each other. They are one and the same program.
I will return to the meaning of this a little later ...
In BASH and other shells like Bourne, the if
command only runs the command, and if the command returns an exit code of 0
, it runs the commands in the if
clause. If the command does not return exit code 0
, it skips the commands in the if
clause and executes the commands in the else
clause if it exists.
Thus, this is also true:
if sleep 2 then echo "That was a good nap!" fi
Your computer executes the sleep 2
command, which (if the sleep command exists) will return a zero exit code and continue the echo. It was a good dream!
What the if
command really does. It executes the given command and checks the exit code.
Now back to [
...
You can see the man page for the test command. You can see that the test
command seems to have the same test types as the [...]
in the if statement. In fact, in the original Bourne shell (from which BASH is derived), this is the same command structure:
if test -f $my_file then echo "File $my_file exists" else echo "There is no file $my_file" fi if [ -f $my_file ] then echo "File $my_file exists" else echo "There is no file $my_file" fi
In fact, in the original Bourne shell, you needed to use the test
command, not the square brackets.
So, back to your original question. -a
and -o
are the parameters of the test command (see the test
page. For example, your if
could be written as follows:
if test $testnum4 -eq 0 -a $testnum100 -ne 0 || test $testnum400 -eq 0 then echo 0 fi
However, &&
and ||
are not parameters of the test command, therefore they cannot be used inside the test command.
Note that [
is a built-in command in BASH, so BASH does not execute /bin/[
as it would in the original Bourne shell. However, it is still the same command as echo
, a built-in command in BASH, although /bin/echo
also exists.