if 條件判斷式

  1. 語法一:if ... then 當符合條件判斷時,就進行某項工作。
    if [ 條件判斷式 ]; then
            當條件判斷式成立時,可以進行的指令工作內容;
    fi
    
  2. 範例:輸入大小寫 y 或 n,條件判斷使用 && 做 AND,|| 做 OR 的條件判斷。
    [dywang@dywmac zzz]$ vim sh06.sh
    [dywang@dywmac zzz]$ cat sh06.sh
    #!/bin/bash
    
    read -p "Please input (Y/N): " yn
    
    if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
    	echo "OK, continue"
    	exit 0
    fi
    if [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
    	echo "Oh, interrupt!"
    	exit 0
    fi
    echo "I don't know what is your choise" && exit 0
    
  3. 執行結果。
    [dywang@dywmac zzz]$ sh sh06.sh 
    Please input (Y/N): y
    OK, continue
    [dywang@dywmac zzz]$ sh sh06.sh 
    Please input (Y/N): n
    Oh, interrupt!
    [dywang@dywmac zzz]$ sh sh06.sh 
    Please input (Y/N): q
    I don't know what is your choise
    
  4. 語法二:if .. else ..fi
    if [ 條件判斷式 ]; then
        當條件判斷式成立時,可以進行的指令工作內容;
    else
        當條件判斷式不成立時,可以進行的指令工作內容;
    fi
    
  5. 語法三:if .. elif.. else.. fi
    if [ 條件判斷式一 ]; then
        當條件判斷式一成立時,可以進行的指令工作內容;
    elif [ 條件判斷式二 ]; then
        當條件判斷式二成立時,可以進行的指令工作內容;
    else
        當條件判斷式一與二均不成立時,可以進行的指令工作內容;
    fi
    
  6. 例題:改寫 sh06.sh 成 sh06-1.sh:
    [dywang@dywmac zzz]$ vim sh06-1.sh
    [dywang@dywmac zzz]$ cat sh06-1.sh
    #!/bin/bash
    
    read -p "Please input (Y/N): " yn
    
    if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
    	echo "OK, continue"
    elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
    	echo "Oh, interrupt!"
    else
    	echo "I don't know what is your choise"
    fi
    
  7. 執行結果。
    [dywang@dywmac zzz]$ sh sh06-1.sh 
    Please input (Y/N): Y
    OK, continue
    [dywang@dywmac zzz]$ sh sh06-1.sh 
    Please input (Y/N): N
    Oh, interrupt!
    [dywang@dywmac zzz]$ sh sh06-1.sh 
    Please input (Y/N): 
    I don't know what is your choise
    
  8. 例題:偵測輸入的參數是否為 hello。
    1. 如果是,顯示 "Hello, how are you?";
    2. 如果沒有加任何參數,提示使用者必須要使用的參數下達法;
    3. 而如果加入的參數不是 hello ,就提醒使用者僅能使用 hello 為參數。
    [dywang@dywmac zzz]$ vim sh07.sh
    [dywang@dywmac zzz]$ cat sh07.sh
    #!/bin/bash
    
    if [ "$1" == "hello" ]; then
    	echo "Hello, how are you?"
    elif [ -z "$1" ]; then
    	echo "You MUST input parameters, ex> $0 someword"
    else
    	echo "The only parameter is 'hello'"
    fi
    
  9. 執行結果。
    [dywang@dywmac zzz]$ sh sh07.sh
    You MUST input parameters, ex> sh07.sh someword
    [dywang@dywmac zzz]$ sh sh07.sh someword
    The only parameter is 'hello'
    [dywang@dywmac zzz]$ sh sh07.sh hello
    Hello, how are you?