Shell中的if else语句 while语句

时间:2023-02-09 20:41:59

Shell中可以使用"[ ]"进行数据判断,“[ ]”的用法跟test基本一致。

使用“[ ]”时要注意三点(来自鸟哥):

1、在中括号"[]"内的每个组件都需要有空格键来分割。

2、在中括号内的变量,最好都以双引号括起来。

3、在中括号内的常量,最好都以单引号或双引号括起来

if else语句的结构为:

if [ condition ]; then

        #some statements

elif [ condition ]; then

        #some statements

else

        #some statements

fi

下面是一个小例子,其中[ "$yn" == "Y" ] || [ "$yn" == "y" ] 等价于[ "$yn" == "Y" -o "$yn" == "y" ],“-o”表示“或”,连接两个判断。

#!/bin/bash

#read user's input and do something
read -p "please input (Y/N):" yn

if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
        echo "OK, you say yes."
elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
        echo "NO? goodbye."
else
        echo "I don't know what you say"
fi

#test whether a directory exist,if not,create it
if [ ! -d "keystoneclient" ]; then
        mkdir keystoneclient
fi

while语句的基本结构为:

while [ condtion ]

do

        #some statements

done

下面是一个小例子:

#!/bin/bash

while [ "$yn" != "yes" -a "$yn" != "YES" ]
do
        read -p "please input YSE or yes to stop this loop." yn
done

echo "OK, you input the correct answer."
其中while语句中加入sleep语句可以构造一个简单的计时器,sleep的单位是秒.如下面的例子,每隔一秒打印一下时间。

#!/bin/bash

while [ 1 ]
do
        date
        sleep 1
done