Friday, October 9, 2009

Linux - Bash Shell Scripting - If Statements

The syntax of the if statement is,

if [ conditional-expression ]; then 
   some commands
fi

or

if [ conditional-expression ]; then
   some commands
else
   some other commands
fi

The character "[" actually refers to a built-in Bash command—it is a synonym for another command named test. The result of the conditional expression is 0 or nonzero with 0 being false and nonzero being true. Some examples,

Use VI to edit if.sh
--------------------------------
today=0
if [ $today = 1 ]; then
   echo "today = 1"
else
   echo "today <> 1"
fi
--------------------------------
$ chmod 755 if.sh
$ ./if.sh
today <> 1

Since using [ ] is equivalent to using test,

today=0
if test $today = 1; then
   echo "today = 1"
else
   echo "today <> 1"
fi

The test command has command line options for checking the status of files, e.g.,

test -d file
True if file is a directory

test -e file 
True if file exists

test -r file
True if file exists and is readable

test -s file
True if file exists and has size > 0

test -w file
True if file exists and is writable.

test -x file
True if file exists and is executable

Multiple conditions can be checked using -a (and) and -o (or), e.g.,

if test -e if.sh -a -x if.sh; then
   echo "if.sh is an executable"
else
   echo "if.sh either does not exist or it is not an executable"
fi

In a schell script, the ! symbol is used as the NOT logical operator, e.g.,

if [ ! -d src ]; then
   echo '"'src'"' does not exist, creating directory.
   mkdir src
fi

To learn more about conditional expressions I suggest you try $ man test.

No comments:

Post a Comment