2018最新linux云计算集群架构师-第一阶段-Linux操作系统入门到精通-第20章-条件判断和流程控制语句If-流程控制语句if
流程控制语句if
1.语法格式
if 条件
then
commands
fi
2.if语句流程图

注:根据我们的命令退出码来进行判断(echo $? =0),如果是0,那么就会执行then后面的命令
#实例1
vim if-1.sh
#内容如下
#!/bin/bash
if ls /mnt
then
echo "it's ok"
fi
#运行
bash !$
3.双分支if语句
语法格式
if command
then
commands
else
commands
fi

#实例2
cat if-2.sh
#内容如下
#!/bin/bash
if grep root /etc/passwd
then
echo "it's ok"
else
echo "it's err"
fi
#运行
sh if-2.sh
#实例3
cat if-3.sh
#内容如下
#!/bin/bash
if grep xuegod /etc/passwd
then
echo "it's ok"
else
echo "it's err"
fi
#运行
sh if-3.sh
4.多分支if语句
语法结构
if 条件测试操作1
then
commands
elif 条件测试操作2
then
commands
elif 条件测试操作3
then
commands
.......
else
commands
fi

#判断用户在系统中是否存在,是否有家目录
#实例4
cat if-4.sh
#内容如下
#!/bin/bash
read -p "input a user:" tu
if grep $tu /etc/passwd
then
echo "the user $tu exists on this system"
elif ls -d /home/$tu
then
echo "the user $tu not exists on this system"
echo "$tu has a home directory"
else
echo "the user $tu not exists on this system"
echo "$tu not has a direcotry"
fi
#运行
sh if-4.sh
posted on 2019-11-22 19:32 herisson_pan 阅读(12) 评论(0) 收藏 举报
浙公网安备 33010602011771号