Programming Tutorials

(追記) (追記ここまで)

Multilevel if-then-else in Linux Shell Script

By: Dorris in Linux Tutorials on 2011年01月15日 [フレーム]

Syntax:

 if condition
 then
 condition is zero (true - 0)
 execute all commands up to elif statement
 elif condition1 
 then
 condition1 is zero (true - 0)
 execute all commands up to elif statement 
 elif condition2
 then
 condition2 is zero (true - 0)
 execute all commands up to elif statement 
 else
 None of the above condtion,condtion1,condtion2 are true (i.e. 
 all of the above nonzero or false)
 execute all commands up to fi
 fi

For multilevel if-then-else statement try the following script:

$ cat > elf
#
#!/bin/sh
# Script to test if..elif...else
#
if [ 1ドル -gt 0 ]; then
echo "1ドル is positive"
elif [ 1ドル -lt 0 ]
then
echo "1ドル is negative"
elif [ 1ドル -eq 0 ]
then
echo "1ドル is zero"
else
echo "Opps! 1ドル is not number, give number"
fi

Try above script as follows:

$ chmod 755 elf
$ ./elf 1
$ ./elf -2
$ ./elf 0
$ ./elf a

Here o/p for last sample run:

./elf: [: -gt: unary operator expected
./elf: [: -lt: unary operator expected
./elf: [: -eq: unary operator expected
Opps! a is not number, give number

Above program gives error for last run, here integer comparison is expected therefore error like "./elf: [: -gt: unary operator expected" occurs, but still our program notify this error to user by providing message "Oopps! a is not number, give number".




(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Linux )

Latest Articles (in Linux)

(追記) (追記ここまで)
(追記) (追記ここまで)

Related Tutorials

AltStyle によって変換されたページ (->オリジナル) /