
Shell if 语句通过通配符与关系运算符判断表达式真假来决定执行什么分支。有三种 if ... else 语句:
if ... fi 语句; if ... else ... fi 语句; if ... elif ... else ... fi 语句。
首先应该记住if和fi成对出现。先看一个简单脚本。

#表达式语句结构
if <条件表达式> ;then
指令
fi
#上下两条语句等价
if <条件表达式>
then
指令
fi
#判断输入是否为yes,没有判断其他输入操作
[root@promote ~]# cat testifv1.0.sh
#!/bin/bash
read -p "please input yes or no: " input
if [ $input == "yes" ] ;then
echo "yes"
fi
#请勿直接回车
[root@promote ~]# bash testifv1.0.sh
please input yes or no: yes
yes
[root@promote ~]#
if语句条件表达式为真时,执行后续语句,为假时,不执行任何操作;语句结束。单分支结构。
再看一个稍微复杂代码。

[root@promote ~]# cat testifv1.1.sh
#!/bin/bash
read -p "please input yes or no: " input ;
if [ $input == "yes" -o $input == "y" ]
then
echo "yes"
fi
[root@promote ~]# vim testifv1.2.sh
[root@promote ~]# bash testifv1.2.sh
please input yes or no: y
yes
[root@promote ~]#
[root@promote ~]# bash testifv1.2.sh
please input yes or no: n
[root@promote ~]#
if else 语句是双分支结构。含有两个判断结构,判断条件能否满足任意条件,满足if then语句块直接执行语句,else执行另一个语句。语句结构类比单分支结构。
[root@promote ~]# cat testifv1.3.sh
read -p "please input yes or no: " input ;
if [ $input == "yes" -o $input == "y" ]
then
echo "yes"
else
echo "no yes"
fi
[root@promote ~]# bash testifv1.3.sh
please input yes or no: n
no yes
[root@promote ~]# bash testifv1.3.sh
please input yes or no: yes
yes
[root@promote ~]#

需要留意else 无需判断,直接接语句。
if else子句判断条件更多shell 编程 ifshell 编程 if,可以称为多分支结构。
[root@promote ~]# cat testifv1.4.sh
#!/bin/bash
read -p "please input yes or no: " input
if [ $input == "yes" -o $input == "y" ]
then
echo "yes"
elif [ $input == "no" -o $input == "n" ]
then
echo "no"
else
echo "not yes and no"
fi
[root@promote ~]#
[root@promote ~]# bash testifv1.4.sh
please input yes or no: yes
yes
[root@promote ~]# bash testifv1.4.sh
please input yes or no: y
yes
[root@promote ~]# vim testifv1.4.sh
[root@promote ~]# bash testifv1.4.sh
please input yes or no: no
no
[root@promote ~]# bash testifv1.4.sh
please input yes or no: n
no
[root@promote ~]# bash testifv1.4.sh
please input yes or no: ssss
not yes and no

再看几个简单例子。
#判断是否为文件
#!/bin/bash
if [ -f /etc/hosts ]
then
echo "is file"
fi
#判断是否是root用户
[root@promote ~]# cat isroot.sh
#!/bin/bash
if [ "$(whoami)"=="root" ]
then
echo "root user"
else
"not root user"
fi
[root@promote ~]# bash isroot.sh
root user
米鼠网自创立以来始终致力于涉足硬件工程、人才招募、软件商城等,始终秉持“的服务,易用的产品”的经营模式,以“提供高品质的服务、满足用户的意愿、携手共建共赢”为企业目标,为美国境内企业提供国际化、化、个性化、的硬件工程解决方案,我司拥有一流的项目总监团队,具备出众的硬件工程设计和推进素质,为全国不同行业用户提供优质的产品和服务,得到了用户的广泛称赞。
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-122010-1.html
图四炸了