Contents /
Previous /
Next
If Conditionals
The if command executes a number of commands
(all the lines between the if and the fi)
if a condition is met.
test ... or [] ... can be used to express the conditon.
if [ $A -le $B ] ; then
echo 'A < B'
else
echo 'B < A'
fi
Alternative syntax:
if [...]
then
...
else
...
fi
The if command understands nothing of arithmetic.
It executes the command test and tests the exit code.
If the exit code is zero, then the command is
considered to be successful and if proceeds with
the body of the if statement block.
If can equally well be used with any command.
For example (conditionally add /usr/local/bin
if grep does not find it in PATH):
if echo "$PATH" | grep -qwv /usr/local/bin ; then
export PATH="$PATH:/usr/local/bin"
fi