位置參數(Position Parameters) 及 位置變數(Position Variables)
 
   
當使用者下一個指令時,後面經常會給一些參數,稱為位置參數 (Position Parameters),例如輸入資料的檔案名稱等。而 shell script 必須能取得這些參數,憑以執行使用者交付的任務。 Shell 會主動取得這些參數,然後放在幾個特殊系統變數內,稱為 「位置變數」 (Position Variable)內,對應如下:
指令 command arg1 arg2 ...... ...... arg9
Shell Script 內部 $0 $1 $2 .... .... $9
其中 $0 是指令名稱,如是外部指令,則為執行檔之檔案名稱。

例: position-var-example
echo first arg is $1
echo tenth arg is ${10} 
for i in $1 $2 $3 $4 $5
do
grep "^$i" /etc/passwd
done

 
 
特殊變數 $* 是一個字串存有所有的 position variables
for i  in $*
do
grep "^$i" /etc/passwd
done
for i 
do
grep "^$i" /etc/passwd
done
 
   
有關 for 迴圈的介紹請參見相關章節

 
 
特殊變數 $# 是一個字串記錄了position variable 的數量
if [ $# -eq 0 ]
then
 echo Usage: ........
 exit 1
else
_......
_.....
fi
 
   
有關 if then else 的介紹請參見相關章節
 
 
Position variables 是 readonly, 但可用 'set' 重設,方法如下:
set string
如此$*的值即為string,而分解後則會放入對應的 position variables。
例: set-var 執行結果
set `date`; echo $6 $2 $3, $4 2023 Mar 11, 20:41:59

Man Page of 'set'

Web Page Copyright: 亞洲大學資訊電機學院 連耀南 yaonanlien@asia.edu.tw  position.htm,  Thu Sep 7 16:18:52 CST 2023