Saturday, July 5, 2008

Shell Script Condition and Loops

If Else Condition

Case Statement

While loop

For Loop

1. IF Else Condition
Syntax:

if confidion ; then

#command to execute

elif condition then

#commands to execute

else

#commands to execute

fi

To check multiple conditions

If condition1 && condition2; then

#command to execute

elif condition 3 || condition4; then

#commands to execute

fi

if condition are generally used with the test command. Test command test the condition and return true if passed else it return false.

A=0

test a –gt 0 will return true.

There is one more thing similar to test. Square bracket.

[ a –gt 0 ] # remember there space after “[“ and before “]”

This is same as test a –gt 0.

Example:

Type.sh: this program will tell you whether you are pass, fail or distication based on you marks.


if [ $# -ne 1 ]; then # remember the space between if and condition echo "Usage: $0 Marks " exit 1 fi if [ $1 -le 35 ]; then echo "Fail" elif [ $1 -le 70 ]; then echo "PASS" elif [ $1 -le 100 ]; then echo "Distinction " else echo "invalid marks" fi


2. case statement

syntax:

case $variable-name in

pattern1)
command
….
….
Command;;

Pattern2)
command
….
.
command;;

pattern N)
command
….
….
command;;

pattern *) # if none of the above do not pattern matches

Command
….
….
command;;

esac # to end the case statement

Example:

Menu.sh Will execute the commands based on your choise.


echo –e “\t\t Menu “ echo -e “\n 1. List of file \n 2.list of all processes \n 3.User of system”

read choice

case “$choice” in

1) ls –l;;

2) ps –A;;

3) who;;

*) echo “invalid option”


3. While loop

Syntax:

While condition;

Do

# Commands to repeat

Done

Example:

Below program will print 1 to 10 numbers.

Count.sh


a=0 while[ a –lt 10 ]; do

expr a + 1

done


4. For Loop

Syntax:

For { Variable Name } in { list }

do # commands to repeat Done

Example:

Below program will do the same thing what above count.sh is doing


for i in 1 2 3 4 3 6 7 8 9 10; do

echo $i

done


No comments: