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
相關文章
相關標籤/搜索