Shell學習筆記 - 分支語句


一、單分支if語句

1. 語法格式

if [ 條件判斷式 ]; then
    程序
fi

或者

if [ 條件判斷式 ]
    then
    程序
fi

注意:中括號和條件判斷式之間必須有空格

 

2. 示例1:判斷登陸的用戶是否是root

#!/bin/bash

if [ "$USER" == root ];then
    echo "Login User is root"
fi

#########或者#########

#!/bin/bash

if [ "$USER" == root ]
    then
    echo "Login User is root"
fi

 

 

 

3. 示例2:判斷分區使用率

#!/bin/bash

test=$(df -h | grep sda1 | awk '{print $5}' | cut -d '%' -f 1)

if [ $test -ge 90 ];then
    echo "Warning! /dev/sda1 is full!"
fi

 

二、雙分支if語句

1. 語法格式

if [ 條件判斷式 ]; then
    條件成立時,執行的程序
    else
    條件不成立時,執行的程序
fi

或者

if [ 條件判斷式 ]
    then
    條件成立時,執行的程序
    else
    條件不成立時,執行的程序
fi

 

2.  示例1:輸入一個文件,判斷是否存在

#!/bin/bash

read -p "Please input a file:" file

if [ -f $file ]; then
    echo "File: $file exists!"
else
    echo "File: $file not exists!"
fi

 

3. 示例2:判斷apache服務是否啟動了,如果沒有啟動,就代碼啟動

#!/bin/bash

test=$(ps aux | grep httpd | grep -v 'grep' | wc -l)

if [ $test -gt 0 ]; then
    echo "$(date) httpd is running!"
else
    echo "$(date) httpd isn't running, will be started!"
    /etc/init.d/httpd start
fi

 

三、多分支if語句

1. 語法格式

if [ 條件判斷式1 ]; then
    當條件判斷式1成立時,執行程序1
elif [ 條件判斷式2 ]; then
    當條件判斷式2成立時,執行程序2
.....省略更多條件.....
else
    當所有條件都不成立時,最后執行此程序
fi

 

2. 示例:實現計算器

#!/bin/bash

# 輸入數字a,數字b和操作符
read -p "Please input number a:" a
read -p "Please input number b:" b
read -p "Please input operator[+|-|*|/]:" opt

# 判斷輸入內容的正確性
testa=$(echo $a | sed 's/[0-9]//g')
testb=$(echo $a | sed 's/[0-9]//g')
testopt=$(echo $opt | sed 's/[+|\-|*|\/]//g')

if [ -n "$testa" -o -n "$testb" -o -n "$testopt" ]; then
    echo "input content is error!"
    exit 1
elif [ "$opt" == "+" ]; then
    result=$(($a+$b))
elif [ "$opt" == "-" ]; then
    result=$(($a-$b))
elif [ "$opt" == "*" ]; then
    result=$(($a*$b))
else
    result=$(($a/$b))
fi

echo "a $opt b = $result"

 

 

四、case語句

case語句和if...elif...else語句都是多分支條件語句,不過和if多分支條件語句不同的是,case語句只能判斷一種條件關系,而if語句可以判斷多種條件關系。

1. 語法格式

case $變量名 in
"值1")
    如果變量的值等於值1,則執行程序1
    ;;
"值2")
    如果變量的值等於值2,則執行程序2
    ;;
.....省略其他分支.....
*)
    如果變量的值都不是以上的值,則執行此程序
    ;;
esac

 

2. 示例:判斷用戶輸入

#!/bin/bash

read -p "Please choose yes/no:" cmd

case $cmd in 
"yes")
    echo "Your choose is yes!"
    ;;
"no")
    echo "Your choose is no!"
    ;;
*)
    echo "Your choose is error!"
    ;;
esac

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM