if 语句语法格式:
if condition
then
command1
command2
...
commandN
fi
写成一行(适用于终端命令提示符):
if [ $(ps -ef | grep -c “ssh”) -gt 1 ]; then echo “true”; fi
if else-if else 语法格式:
f condition1
then
command1
elif condition2
then
command2
else
commandN
以下实例判断两个变量是否相等:
[syf@myhostname ~]$ if [ $a = $b ]
> then
> echo "a=b"
> elif [ $a -lt $b ]
> then
> echo "a<b"
> else
> echo "a>b"
> fi
a=b
if else语句经常与test命令结合使用,如下所示:
num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
echo '两个数字相等!'
else
echo '两个数字不相等!'
fi
for 循环
与其他编程语言类似,Shell支持for循环。
for循环一般格式为:
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
实例:
[syf@myhostname ~]$ for loop in 1 2 3 4
> do
> echo "kdj"
> done
kdj
kdj
kdj
kdj
while 语句
while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令通常为测试条件。其格式为:
while condition
do
command
done
实例:
[syf@myhostname ~]$ while(($int<=5))
> do
> echo ${int}
> let "int++"
> done
1
2
3
4
5
使用中使用了 Bash let 命令,它用于执行一个或多个表达式,变量计算中不需要加上 $ 来表示变量,具体可查阅:Bash let 命令