來源:https://blog.csdn.net/Powerful_Fyshell
格式1:if 條件 ; then 語句; fibash
#!/bin/bash read -p "input a number:" n if [ $n -gt 5 ] then echo "1" fi
格式2:if 條件; then 語句; else 語句; fisocket
#!/bin/bash read -p "input a number:" n if [ $n -gt 5 ] then echo "1" else echo "2" fi
格式3:if …; then … ;elif …; then …; else …; fi.net
#!/bin/bash read -p "input a number:" n if [ $n -gt 90 ] then echo "A" elif [ $n -gt 70 ] then echo "B" else echo "C" fi
格式4:if 中嵌套 ifcode
#!/bin/bash read -p "input a number:" n if [ $n -gt 70 ] then echo "OK" if [ $n -gt 90 ] then echo "A" elif [ $n -gt 80 ] then echo "B" else echo "C" fi else echo "???" fi
補充: -gt 大於(>) -lt 小於 (<) -ge 大於等於 (>=) -le 小於等於 (<=) -eq 等於 (==) -ne 不等於 (!=)對象
可使用 && || 結合多個條件blog
大於5而且小於10:get
if [ $a -gt 5 ] && [ $a -lt 10 ]; then
第二種寫法:input
if [ $a -gt 5 -a $a -lt 10 ]; then
#-a表示:andit
大於5或小於3:
if [ $b -gt 5 ] || [ $b -lt 3 ]; then
第二種寫法:
if [ $b -gt 5 -o $b -lt 3 ]; then
#-o表示or
[ -f file ] 判斷是不是普通文件,且存在 [ -d file ] 判斷是不是目錄,且存在 [ -e file ] 判斷文件或目錄是否存在 [ -r file ] 判斷文件是否可讀 [ -w file ] 判斷文件是否可寫 [ -x file ] 判斷文件是否可執行
補充: 1.若是判斷對象爲socket等特殊文件,可使用-e判斷是否存在
2.root用戶對文件的讀寫比較特殊,即便一個文件沒有給root用戶讀或者寫的權限,root用戶照樣能夠讀或者寫(x:執行權限除外)
3.取反使用感嘆號:
if [ ! -f filename ]
判斷變量爲空時:
if [ -z "$a" ]; then ...
判斷變量不爲空時:
if [ -n "$a" ]; then ...
判斷命令成功時:
if ls /tmp/test.sh; then ...
#判斷文件是否存在的用法,當ls命令執行成功時,要怎樣...
將產生的信息重定向到/dev/null:
if ls /tmp/test.sh &> /dev/null; then ...
#無論ls命令執行是否成功,都將輸出的信息流寫入到/dev/null,不打印
判斷文件是否包含關鍵字:
if grep -q '123' /tmp/test.sh; then ...
#當文件包含關鍵字時,要怎樣...,-q:包含關鍵字時,不輸出匹配到的信息
if [ $a -gt 5 ]的另外一種寫法:
if (($a>5)); then ...
#[ ] 中不能使用<,>,==,!=,>=,<=這樣的符號,但雙括號中能夠
case 變量名 in value1) command ;; value2) command ;; *) commond ;; esac 在case中,能夠在條件中使用|,表示或的意思: 2|3) command ;;
示例:
#!/bin/bash read -p "input a number: " n #判斷輸入內容是否爲空 if [ -z "$n" ] then echo "Please input a number." exit 1 fi #判斷輸入內容是否含有非數字 n1=`echo $n|sed 's/[0-9]//g'` if [ -n "$n1" ] then echo "Please input a number." exit 1 fi #當輸入內容非空且爲純數字時,開始判斷 if [ $n -lt 60 ] && [ $n -ge 0 ] then t=1 elif [ $n -ge 60 ] && [ $n -lt 80 ] then t=2 elif [ $n -ge 80 ] && [ $n -lt 90 ] then t=3 elif [ $n -ge 90 ] && [ $n -le 100 ] then t=4 else t=0 fi case $t in 1) echo "D" ;; 2) echo "C" ;; 3) echo "B" ;; 4) echo "A" ;; *) echo "The number range must be 0-100." ;; esac