@Amzerik:
You might think that you have asked a very specific question and all you wanted is a specific answer. Now my colleagues are questioning your motives. Please, let me explain.
We oftenly have the case that question "how can i achieve X" is asked because what is really needed is Y but the thread opener is under the (false) impression that X is necessary to achieve Y. It may be that in fact X is a suboptimal way to achieve Y and as soon as we recognize that we try to help the thread opener achieve his goal instead of answering his question. Therefore all the questions about your OS, the version, your true goal, etc.
Regarding your initial question: "if" takes a list of commands as an argument and branches depending on its exit code. The following will work:
if true ; then
echo "tested to TRUE"
else
echo "tested to FALSE"
fi
(Of course, the else-part will never be executed because "true" always returns 0, whereas "false" always returns 1. Replace "true" with "false" to see this effect. "true" and "false" are both commands built for exactly this purpose.)
In shell programming, logical TRUE and FALSE are handled like in C: 0 is TRUE, everything else is FALSE. Now "grep -q" returns "0" when it finds the search pattern in its input and "1" if not. Therefore we could write:
if grep -q "foo" /path/to/file/containing-foo ; then
...
and the if-branch would be executed if the file contains "foo" while the else-part will be executed of the file doesn't contain "foo".
Now, how does that fit in with what we usually see as if-statements?
Originally, there was a command "test": it was fed an expression which evaluated to TRUE or FALSE and returned an exit status depending on this. See the man page for "test" for details. The following should be obvious to you now ("-ge" means "greater or equal"):
if test 1 -ge 0 ; then
echo "yes, it worked"
else
echo "something went wrong"
fi
(By the way, this is why it is a really BAD idea to name a program "test". It will collide with the original "test" from the system, which is still there.)
Now, to let shell code look more like traditional programming languages someone came up with the clever idea to make "[" a link to "test". "test" could now be invoked by "[" too and the following could be written:
if [ 1 -ge 0 ; then
echo "yes, it worked"
else
echo "something went wrong"
fi
but that still looked counter-intuitive, because the opening "[" missed a counterpart. Therefore "test" itself was modified to have "]" as its (last) argument (well, actually only its "["-variant was changed that way). Now the necessary line looked like what we are used to:
if [ 1 -ge 0 ] ; then
echo "yes, it worked"
else
echo "something went wrong"
fi
Notice, this is the reason, why "[" has to be surrounded by spaces. if [ $int1 -ge $int2 ];
will work, whereas if [$int1 -ge $int2];
won't. It is for the same reason that ls -l
works but ls-l
doesn't.
I hope this helps.
bakunin