linux之判断式
1、判斷基礎知識
當要檢測某個文件或者文件d的相關屬性,可以利用 test 命令
[root @loacalhost ~]#test -e /vitest使用 test 命令檢測 目錄vitest是否存在
但是不會顯示任何結果,因此進行改進為有“參數”輸出的形式
[root @loacalhost ~]#test -e /vitest && echo "The dir exist" || echo "Not exist"給出標志判斷表
除了使用test之外,還可以使用 [] 判斷符號進行判斷
[root @loacalhost ~]#[ -z "$HOME" ];echo %?注意:因為中括號 [] 使用的地方很多,常見的有通配符和正則表達式,所以在bash語法重法中使用[] 作為shell的判斷時,必須中括號[]的兩端需要有空格來分割
1、中括號 [] 內的每個組件都需要空格鍵來分割
2、中括號 [] 內的變量,最好都以雙引號括起來
3、中括號 [] 內的常量,最好以雙引號或者單引號括起來
[root @loacalhost ~]#name="rhx" #變量賦值時=左右兩側不能有空格 [root @loacalhost ~]#[ $name == "HOME" ] #判斷時=的左右兩側必須有空格2、條件判斷式
條件判斷式即是滿足某個條件時執行一個動作,不滿足會執行相應的其他動作,下面一一介紹
a、單層 if...then 判斷
if [ 條件判定式 ];then #注意條件判定式左右兩側有空格action #條件成立時,執行action中的操作 fi #結束if判斷,相當于是if左右翻轉示例如下:
#!/bin/bash #program: # This program shows "Hello World!" in your screen #History: #205/08/3 rhx First Release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATHread -p "Please input (Y/N): " ynif [ "$yn" == "Y" ] || [ "$yn" == "y" ];thenecho "Ok ,continue"exit 0 fiif [ "$yn" == "N" ] || [ "$yn" == "n" ];thenecho "Oh interrupt"exit 0 fiecho "I do not know what your choice is "&& exit 0b、多重復雜判斷 if elif else
if [ 條件判定式1 ];then #注意條件1判定式左右兩側有空格action1 #條件成立時,執行action1中的操作 elif [ 條件判定式2 ];then action2 #條件2成立時,執行action2中的操作 fi #結束if判斷,相當于是if左右翻轉 #!/bin/bash #program: # This program shows "Hello World!" in your screen #History: #205/08/3 rhx First Release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATHread -p "Please input (Y/N): " ynif [ "$yn" == "Y" ] || [ "$yn" == "y" ];thenecho "Ok ,continue" elif [ "$yn" == "N" ] || [ "$yn" == "n" ];thenecho "Oh interrupt" fi在shell scripts中,scritpt針對參數有一些特殊設置,參數的對應關系如下,$0表示文件名
/tmp/scrpts opt1 op2 opt3 opt4$0 $1 $2 $3 $4 #!/bin/bash #program: # This program shows "Hello World!" in your screen #History: #205/08/3 rhx First Release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH#read -p "Please input (Y/N): "ynif [ "$1" == "hello" ];thenecho "Hello,how are you ?" elif [ "$1" == "" ];thenecho "You MUST input parameters,ex> {$0 someword}" elseecho "The only parameters is 'hello',ex> {$0 hello}" fic、case ...esac
case $variable in #關鍵字case,變量variable前有符號$"value1") #每個變量的內容建議用雙括號括選起來,關鍵字外面為小括號),注意這里不同于常見的c/c++語言;; #每個類型結束使用連續兩個分號"value2";;*) #最后一個變量內容會用*來表示其他的值,像c/c++中的default選項;; esac #case語法結束示例如下:
#!/bin/bash #program: # This program shows "Hello World!" in your screen #History: #205/08/3 rhx First Release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATHfunction printit(){echo -n "Your choice is " }echo "This program will print your selection!"case $1 in"one")printit;echo $1 | tr 'a-z' 'A-Z';;"two")printit;echo $1 | tr 'a-z' 'A-Z'"three")printit;echo $1 | tr 'a-z' 'A-Z';; *)echo "Usage $0 {one|two|three}";; esacd、利用 function 功能
function funcname () {程序段 }注意function中的$0,$1,$2與script中有所不同
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
- 上一篇: Linux之交互式scripts
- 下一篇: linux之循环