linux關於判斷式的基礎知識講解,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 %
注意:因為中括弧 [] 使用的地方很多,常見的有萬用字元和Regex,所以在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 ReleasePATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/binexport PATHread -p "Please input (Y/N): " ynif [ "$yn" == "Y" ] || [ "$yn" == "y" ];then echo "Ok ,continue"exit 0fiif [ "$yn" == "N" ] || [ "$yn" == "n" ];then echo "Oh interrupt"exit 0fiecho "I do not know what your choice is "&& exit 0
b、多重複雜判斷 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 ReleasePATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/binexport PATHread -p "Please input (Y/N): " ynif [ "$yn" == "Y" ] || [ "$yn" == "y" ];then echo "Ok ,continue"elif [ "$yn" == "N" ] || [ "$yn" == "n" ];then echo "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 ReleasePATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/binexport PATH#read -p "Please input (Y/N): "ynif [ "$1" == "hello" ];then echo "Hello,how are you "elif [ "$1" == "" ];then echo "You MUST input parameters,ex> {$0 someword}"else echo "The only parameters is 'hello',ex> {$0 hello}"fi
c、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 ReleasePATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/binexport 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}" ;;esac
d、利用 function 功能
function funcname () { 程式段}
注意function中的$0,$1,$2與script中有所不同