To explain that i have to dig into UNIX history somewhat:
First: The general form of the if
-statement in Bourne-descendant shells (ksh, bash, [POSIX-]sh, etc.) is:
if command ; then
Which branch of the if
-statement (the "if"- or the "else"-branch) is executed is decided by examining the return code (error level) of the command. The following lines will do absolutely the same, but the latter is preferable because it saves on fork()-calls:
/some/command
if [ $? -eq 0 ] ; then
if /some/command ; then
What is now if [ .... ]
, you might ask.
Because of the mechanism of if
the UNIX designers came up with a clever utility: test
. This command executes all sorts of comparisons and sets its return code according to the result of these comparison. If you wanted to branch on two variables being equal you could do (i have marked bold the test-command and its parameters):
if /usr/bin/test $a -eq $b ; then
Now, this looked a bit unhandy. Therefore a further trick was to create a link /usr/bin/[
to /usr/bin/test
, the line would now look like:
if [ $a -eq $b ; then
But this still was not completely satisfactory, because programmers are religiously raised to close what they open: quotes, brackets, braces, clauses, ....
Therefore, the last twist was to create /usr/bin/[
as a program in its own right which works just like /usr/bin/test
but requires a "]" as the last parameter. Now the code as we know it were possible:
if [ $a -eq $b ] ; then
Notice, though, that "[" is a command and "]" is one of its parameters. Therefore, the following are all syntactically wrong (for obvious reasons):
if [$a -eq $b ] ; then
if[ $a -eq $b ] ; then
if [ $a -eq $b] ; then
OK, this is all good, but what is if [[ ...
then?
In fact "[[" is the same as "[", but as a shell-built-in instead of an external command. Shell developers found out that test
and its companion [
were used so oftenly that they built it into their shells to save on system calls.
Lastly, what is if (( ... ))
now?
Well, the same as i wrote above: if command
, where command is a device in ksh as well as bash: you can do integer math surrounded by double rounded brackets:
(( x += 1 ))
is a legal command and the same as (in fact a substitution for) the (quite old-fashioned) built-in let
:
let x=x+1
Like let
also (( ... ))
has a return code and this is what if
acts upon.
I hope this clears it up a bit.
bakunin