Shell 判斷 if 和分支 case

2021-09-19 20:17:42 字數 3516 閱讀 5969

語法:

if [ 條件判斷式 ];then

# do something

fi

或者

if [ 條件判斷式 ]

then

# do something

fi

案例一,獲取當前使用者名稱,當然用whoami也可:

#!/bin/bash

test=`env | grep "user" | cut -d

"="-f

2`if [ test=="root" ];then

echo

"this user is root"

fi

案例二,檢查磁碟容量:

#!/bin/bash

rate=`df -h | grep "sda1" | awk '' | cut -d

"%"-f

1`if [ $rate

-gt"10" ];then

echo

"/ is full"

fi

ps:

- 條件判斷式就是test命令判斷,可以用test命令替代,中括號中間必須有空格

- -gt 當變數值為空時會報錯

語法:

if [ 條件判斷式 ]

then

...else

...fi

案例三,判斷目錄的屬性:

#!/bin/bash

read -t 30 -p "input a dir:" dir

if [ -d

$dir ]

then

echo

"this is a directory"

else

echo

"no no no "

fi

案例四,判斷tomcat服務是否開啟:

#!/bin/bash

test=`ps aux | grep tomcat | grep -v grep`

if [ -n "$test" ]

then

echo

"tomcat is running"

else

echo

"tomcat is not running"

/etc/init.d/tomcat start

# service tomcat start 不建議使用

echo

"tomcat is started"

fi

ps:

- if判斷中的變數最好加上引號,因為如果變數的值中包含空格,將出現too many arguments錯誤,所以還是寫成if [ -n "$test" ]較安全

語法:

if [ 條件判斷 ]

then

# do something

elif [ 條件判斷 ]

then

# do something

...else

# do something

fi

案例五,簡易計算器:

#!/bin/bash

read -p "please input num1:" num1

read -p "please input operator:" op

read -p "please input num2:" num2

if [ -z "$num1" -o -z "$num2" -o -z "$op" ]

then

echo

"value shoud not be null"

exit

2else

# 把所有數字替換成空,如果替換後不為空,則表示變數中不符合規範

test1=`echo

$num1 | sed 's/[0-9]//g'`

test2=`echo

$num2 | sed 's/[0-9]//g'`

if [ -n "$test1" -o -n "$test2" ];then

echo

"數值格式錯誤"

exit4fi

if [ "$op" == "+" ]

then

result=$(($num1+$num2))

elif [ "$op" == "-" ]

then

result=$(($num1-$num2))

elif [ "$op" == "*" ]

then

result=$(($num1*$num2))

elif [ "$op" == "/" ]

then

let"result=$num1/$num2"

else

echo

"operator is wrong"

exit3fi

fiecho$$

$=$

案例六,判斷檔案型別:

#!/bin/bash

read -p "請輸入檔案或目錄名:" path

if [ -z "$path" ]

then

echo

"請輸入內容!"

exit

10elif [ ! -e

"$path" ]

then

echo

"檔案或目錄不存在"

exit

11elif [ -f

"$path" ]

then

echo

"輸入的是乙個檔案"

elif [ -d

"$path" ]

then

echo

"輸入的是乙個目錄"

else

echo

"輸入的式其他型別的檔案"

fi

語法:

case $變數名 in

"值1")

// do something,變數的值等於值1

;;"值2")

// do something,變數的值等於值2

;;...

*)// do something,變數的值與上面都不同

;;esca

案例

#!/bin/bash

read -p "請輸入 yes/no" result

case

"$result"

in"yes")

echo

"你輸入的式yes"

;;"no")

echo

"你輸入的是no"

;;*)

echo

"請輸入正確的選擇"

esac

06 shell 判斷分支處理

root rocky script cat bmi.sh bin bash read p 請輸入身高 m為單位 high if high 0 2 0 9 then echo 輸入錯誤的身高 exit 1fi read p 請輸入體重 kg為單位 weight if weight 0 9 then e...

Shell指令碼IF條件判斷和判斷條件總結

前言 無論什麼程式語言都離不開條件判斷。shell也不例外。如下 if list then do something here elif list then do another thing here else do something else here fiex1 bin sh system u...

Shell指令碼IF條件判斷和判斷條件總結

自 前言 無論什麼程式語言都離不開條件判斷。shell也不例外。if list then dosomething here elif list then doanother thing here else dosomething else here fi ex1 bin sh system unam...