標籤:
①shell的數值計算
$[[ 空格]$a[空格 ]operator[空格]$b[空格]]
計算時操作符及其運算元必須要用方括弧[]括起來,然後用$作為前置字元,[空格]表示此處空格可有可無
eg: ` a=2;b=3;echo $[ $a + $b] ` #螢幕輸出 5
②指令碼運行時與使用者的互動
` read x `
程式運行到此處時會暫停並提示使用者輸入數值,使用者輸入完畢並斷行符號後,程式將使用者輸入的值賦給x,x為任意變數名
eg: ` read x `
` read -p "please enter a number: " y `
程式運行到此處時,螢幕列印"please enter a number:"並等待使用者輸入,使用者輸入完畢並斷行符號後,程式將使用者輸入的值賦給y,y為任意變數名
③指令碼啟動並執行參數
` ./test.sh Ferir 24 `
執行指令碼時可以給指令碼添加參數,第一個參數為Ferir,在指令碼中用$1擷取,第二個參數為24,在指令碼中用$2擷取,參數個數無限,在指令碼中通過$+參數位元擷取
備忘:$0為指令碼名稱
④if-elif-elif-else-fi
if-fi
` if(($a > 30));then echo $a;fi ` or ` if [ $a -gt 30 ];then echo $a;fi `
if-else-fi
` if(($a = 30));then echo $a;else echo 30;fi ` or ` if [ $a -eq 30 ];then echo $a;else echo 30;fi `
if-elif-elif-else-fi
` if(($a > 30)) && (($a = 30));then echo $a;elif(($a > 20)) || (($a = 20));then echo $[$a+1];else echo ‘Sorry‘;fi `
備忘:如果用方括弧[]包裹條件,則if 與 [之間、運算元與[ 、]之間必須有空格
> *** -gt = *** -eq >= *** -ge <= *** -le < *** -lt != *** -ne
if 判斷文件屬性
` if [ -defrwx filename ] ` -d 存在&&目錄 -e 存在 -f 存在&&普通檔案 -r 可讀 -w 可寫 -x 可執行
⑤case $a in value1) command;; value2) command;; value3) command;; *) command;; esac
` read -p ‘Please input a number: ‘ a;
case $[ $a%2 ] in
0)
echo "The number is even!";;
1)
echo "The number is odd!";;
*)
echo "This is impossible!";;
esac `
SHELL指令碼的文法知識2