歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> UNIX Shell控制結構—IF

UNIX Shell控制結構—IF

日期:2017/3/1 10:02:11   编辑:SHELL編程

流控制(Decision Making)
IF語句有三種格式:
第一種:if ... fi statement

下面是一個實例:

cat if1.sh
#!/bin/sh
a=10
b=20
#①
if [ $a -eq $b ]; then
echo "a is equal to b";
fi
if [ $a -gt $b ]; then
echo "a is great than b";
fi
#②
if [ $a -lt $b ]
then
echo "a is less than b";
fi
# the EOF

注意:
①條件和處理命令分開的一種寫法:
if 條件; then
處理命令
fi
②條件和處理命令分開的另一種寫法:
if 條件
then
處理命令
fi
這裡需要根據個人習慣去選擇。

上面的例子中,變量的值是賦死了的,若要給此腳本傳遞兩個參數,可做如下修改:

cat if1.sh
#!/bin/sh
# a=10
# b=20
if [ $1 -eq $2 ]; then
echo "the first number is equal to the second";
fi
if [ $1 -gt $2 ]; then
echo "the first number is great than the second";
fi
if [ $1 -lt $2 ]
then
echo "the first number is less than the second";
fi
# the EOF

給腳本傳遞參數,只需要在sh命令後面添加即可,使用空格隔開:

sh if1.sh 1 2
the first number is less than the second
sh if1.sh 12 1
the first number is great than the second
sh if1.sh 1 1
the first number is equal to the second

Copyright © Linux教程網 All Rights Reserved