標籤:
Shell script 的預設變數($0, $1...)
我們知道指令可以帶有選項與參數,例如 ls -la 可以察看包含隱藏檔案的所有屬性與許可權。那麼 shell script 能不能在指令檔名後面帶有參數呢?很有趣喔!舉例來說,如果你想要重新啟動系統登入檔案的功能,可以這樣做:
[[email protected] ~]# file /etc/init.d/syslog
/etc/init.d/syslog: Bourne-Again shell script text executable
# 使用 file 來查詢後,系統告知這個檔案是個 bash 的可執行 script 喔!
[[email protected] ~]# /etc/init.d/syslog restart
restart 是重新啟動的意思,上面的指令可以”重新啟動 /etc/init.d/syslog 這個程式”的意思! 唔!那麼如果你在 /etc/init.d/syslog 後面加上 stop 呢?沒錯!就可以直接關閉該服務了!這麼神奇啊? 沒錯啊!如果你要依據程式的執行給予一些變數去進行不同的任務時,本章一開始是使用 read 的功能!但 read 功能的問題是你得要手動由鍵盤輸入一些判斷式。如果透過指令後面接參數, 那麼一個指令就能夠處理完畢而不需要手動再次輸入一些變數行為!這樣執行指令會比較簡單方便啦!
script 是怎麼達成這個功能的呢?其實 script 針對參數已經有設定好一些變數名稱了!對應如下:
/path/to/scriptname opt1 opt2 opt3 opt4
$0 $1 $2 $3 $4
這樣夠清楚了吧?執行的指令檔名為 $0 這個變數,第一個接的參數就是 $1 啊~ 所以,只要我們在 script 裡面善用 $1 的話,就可以很簡單的立即執行某些指令功能了!除了這些數位變數之外, 我們還有一些較為特殊的變數可以在 script 內使用來調用這些參數喔!
$# :代表後接的參數”個數”,以上表為例這裡顯示為” 4 “;
[email protected] :代表” "$1" "$2" "$3" "$4" “之意,每個變數是獨立的(用雙引號括起來);
$* :代表” "$1c$2c$3c$4" “,其中 c 為分隔字元,預設為空白格鍵, 所以本例中代表” "$1 $2 $3 $4" “之意。
那個 [email protected] 與 $* 基本上還是有所不同啦!不過,一般使用方式下可以直接記憶 [email protected] 即可!
好了,來做個例子吧~假設我要執行一個可以攜帶參數的 script ,執行該指令碼後螢幕會顯示如下的資料:
程式的檔案名稱為何?
共有幾個參數?
若參數的個數小於 2 則告知使用者參數數量太少
全部的參數內容為何?
第一個參數為何?
第二個參數為何 ?
[[email protected] scripts]# vi sh07.sh
#!/bin/bash
# Program:
# Program shows the script name, parameters...
# History:
echo "The script name is ==> $0"
echo "Total parameter number is ==> $#"
[ "$#" -lt 2 ] && echo "The number of parameter is less than 2. Stop here." && exit 0
echo "Your whole parameter is ==> ‘[email protected]‘"
echo "The 1st parameter ==> $1"
echo "The 2nd parameter ==> $2"
來源程式如下:
1 echo "The script name is ==> $0"2 echo "Total parameter number is ==> $#"3 [ "$#" -lt 2 ] && echo "The number of parameter is less than 2. Stop here." && exit 04 echo "Your whole parameter is ==> ‘[email protected]‘"5 echo "The 1st parameter ==> $1"6 echo "The 2nd parameter ==> $2"
建立shell檔案,並命名為shell07.sh
斷行符號(Enter),用vi編輯器編寫shell07.sh
執行結果如下:
shell編程 Shell script 的預設變數($0, $1...)