CentOS 7 Shell脚本编程第十一讲 if 语句和简单练习

Shell if 语句经过表达式与关系运算符判断表达式真假来决定执行哪一个分支。有三种 if ... else 语句:vim

    if ... fi 语句;
    if ... else ... fi 语句;
    if ... elif ... else ... fi 语句。bash

首先须要记住if和fi成对出现。先看一个简单脚本。spa

#表达式语句结构

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语句条件表达式为真时,执行后续语句,为假时,不执行任何操做;语句结束。单分支结构。code

再看一个稍微复杂代码。input

[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执行另外一个语句。语句结构类比单分支结构。test

[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 无需判断,直接接语句。file

if else语句判断条件更多,能够称为多分支结构。im

[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
相关文章
相关标签/搜索