Sunday, April 12, 2009

If construct in shell script

If condition in shell script is used to check whether a particular condition is true. 
The syntax of if construct is:

if condition  
then
do something
fi

If the "condition" of if  is true or if exit status is zero then statements inside do something(if block) is executed, otherwise control is passed to the statement after "fi".


If value of $? is zero(0) then if block is executed, for non-zero value if block is not executed.

Below is an example of if construct based on both condition and exit status.
Condition Example:
Below is the contents of if_construct.sh script. 

While running the script if you give a argument then greater than or equal 10 then if condition is satisfied and a message is displayed. 

If you give argument less than 10 then if condition will not be satisfied and statements inside if block will not also be executed.

If you don't give any argument error will be returned.
Each secnarios are shown below with examples.

# cat if_construct.sh
echo "To run if statementt you must pass one argument"
echo "Your supplied first argument: $1"
if [ "$1" -ge "10" ]
then
echo "You supplied number more than 10 or 10"
fi

#chmod +x  if_construct.sh

# ./if_construct.sh
To run if statementt you must pass one argument
Your supplied first argument:
./if_construct.sh: line 3: [: : integer expression expected

# ./if_construct.sh 13
To run if statementt you must pass one argument
Your supplied first argument: 13
You supplied number more than 10 or 10

# ./if_construct.sh 1
To run if statementt you must pass one argument
Your supplied first argument: 1

Exit Status Example:
If linux command is successful then exit status is 0 otherwise it is non-zero value. Within if condition if exit status become 0 i.e command is executed successful then statement within if construct is executed.
In the following script, script will prompt for a filename. After supplying filename if it exist within current location then file contents are shown and then a message.

# cat if_exit_status.sh
echo "This script will see whether file exists in current directory"
echo -n "Enter filename :"
read filename;
if cat $filename
then
echo "File $filename found."
fi

# chmod +x if_exit_status.sh

# ./if_exit_status.sh
This script will see whether file exists in current directory
Enter filename :if_construct.sh
echo "To run if statementt you must pass one argument"
if [ "$1" -ge "10" ]
echo "Your supplied first argument: $1"
then
echo "You supplied number more than 10"
fi

File if_construct.sh found.
# ./if_exit_status.sh
This script will see whether file exists in current directory
Enter filename :file_does_not_exist
cat: file_does_not_exist: No such file or directory

Related Documents

No comments:

Post a Comment