if ... then
當符合條件判斷時,就進行某項工作。
if [ 條件判斷式 ]; then 當條件判斷式成立時,可以進行的指令工作內容; fi
&&
做 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
[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
if .. else ..fi
if [ 條件判斷式 ]; then 當條件判斷式成立時,可以進行的指令工作內容; else 當條件判斷式不成立時,可以進行的指令工作內容; fi
if .. elif.. else.. fi
if [ 條件判斷式一 ]; then 當條件判斷式一成立時,可以進行的指令工作內容; elif [ 條件判斷式二 ]; then 當條件判斷式二成立時,可以進行的指令工作內容; else 當條件判斷式一與二均不成立時,可以進行的指令工作內容; fi
[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
[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
[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
[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?