流程控制语句
if条件测试语句
if语句分为单分支结构、双分支结构、多分支结构
if的单分支结构由if-then-fi关键词组成,相当于如果...那么...,只有当条件成立时才会执行对应的命令。
使用该语句判断某个文件夹是否存在,不存在则创建一个新的文件夹。
[root@linux bashScript]# cat mkcdrom.sh
#!/bin/bash
DIR='/opt/cdrom'
if [ ! -e $DIR ]
then
mkdir -p $DIR
fi
[root@linux bashScript]# bash mkcdrom.sh
[root@linux bashScript]# cd ..
[root@linux opt]# ll
总用量 276
drwxr-xr-x. 2 root root 42 5月 20 19:21 bashScript
drwxr-xr-x. 2 root root 6 5月 20 19:21 cdrom
-rw-r--r--. 1 root root 281538 5月 13 18:52 data.txt
根据打印的结果看出在/opt目录下创建了一个新的cdrom目录
if的双分支结构由if-then-else-fi关键词组成,该语句会先进行一次条件匹配来执行相应的命令,如果不匹配就执行不匹配的命令,相当于如果...那么...或者...那么...。
[root@linux bashScript]# cat mkhost.sh
#!/bin/bash
# -c : 链接ip失败时尝试的次数
# -i : 每个数据包发送的间隔
# -W : 等待超时的时间
ping -c 3 -i 0.2 -W $1 &> /dev/null
if [ $? -eq 0 ]
then
echo "Host $1 is On-line."
else
echo "Host $1 is Off-line."
fi
[root@linux bashScript]# bash mkhost.sh 192.168.10.10
Host 192.168.10.10 is On-line.
本机的Ip为192.168.10.10
if的多分支结构由if-then-elif-then-else-fi关键词组成,该语句会进行多次匹配,相当于如果...那么...如果...那么...。
[root@linux bashScript]# cat chkscore.sh
#!/bin/bash
read -p "Enter your score (0-100):" GRADE
if [ $GRADE -gt 85 ] && [ $GRADE -le 100 ]
then
echo "$GRADE is Excellent."
elif [ $GRADE -gt 70 ] && [ $GRADE -lt 85 ]
then
echo "$GRADE is Pass."
else
echo "$GRADE is Fail."
fi
[root@linux bashScript]# bash chkscore.sh
Enter your score (0-100):77
77 is Pass.
for循环
for循环语句允许脚本一次性读取多个信息,然后逐一进行操作处理。
for语法:
for 变量名 in 取值列表
do
命令块
done
[root@linux bashScript]# cat user.txt
andy
barry
carl
duke
eric
gerrge
[root@linux bashScript]# cat user.sh
#!/bin/bash
for uname in `cat user.txt`
do
if [ $? -eq 0 ]
then
echo "Already exists."
else
echo "$uname"
fi
done
[root@linux bashScript]# bash user.sh
Enter the user password:1
Already exists.
Already exists.
Already exists.
Already exists.
Already exists.
Already exists.