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

範例: position-var-example
echo first arg is $1
echo tenth arg is ${10} 

 
 
特殊變數 $* 是一個字串,儲存有所有的引數, 下面三個 script 是相同的:
#Assume five arguments
#-------------------------
for i in $1 $2 $3 $4 $5
do
   grep "^$i" /etc/passwd
done
#same as previous script
#-------------------------
for i  in $*
do
grep "^$i" /etc/passwd
done
#same as previous script
#-------------------------
for i 
do
grep "^$i" /etc/passwd
done
#-------------------------
#"for i" 後面的 argument list 可以省略
 
   
有關 for 迴圈的介紹請參見相關章節

 
 
特殊變數 $# 是一個字串,記錄了位置變數的數量
if [ $# -eq 0 ]
then
 echo Usage: ........
 exit 1
else
_......
_.....
fi
 
   
有關 if-then-else 的介紹請參見相關章節
 
 
位置變數雖是唯讀變數, 但可用 'set' 重設,方法如下:
set string
如此$*的值即為string,而分解後則會放入對應的位置變數。例如:
指令 執行結果
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,  Sun Dec 14 23:14:45 CST 2025