以前的教程中說(shuō)過(guò)有關(guān)在變量名中使用某些非字母數(shù)字字符。這是因?yàn)檫@些字符中使用特殊的Unix變量的名稱。這些變量被保留用于特定功能。
例如,$字符表示進(jìn)程ID號(hào),或PID,在當(dāng)前shell:
$echo $$
上面的命令將寫入在當(dāng)前shell的PID:
29949
以下下表顯示了一些特殊的變量,你可以在你的shell腳本中使用:
變量 | 描述 |
---|---|
$0 | The filename of the current script. |
$n | These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on). |
$# | The number of arguments supplied to a script. |
$* | All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2. |
$@ | All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2. |
$? | The exit status of the last command executed. |
$$ | The process number of the current shell. For shell scripts, this is the process ID under which they are executing. |
$! | The process number of the last background command. |
該命令行參數(shù) $1, $2, $3,...$9 是位置參數(shù),與0美元指向?qū)嶋H的命令,程序,shell腳本,函數(shù)和 $1, $2, $3,...$9 作為參數(shù)的命令。
下面的腳本使用命令行相關(guān)的各種特殊變量:
#!/bin/sh
echo "File Name: $0"
echo "First Parameter : $1"
echo "First Parameter : $2"
echo "Quoted Values: $@"
echo "Quoted Values: $*"
echo "Total Number of Parameters : $#"
下面是一個(gè)示例運(yùn)行上面的腳本:
$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2
有特殊的參數(shù),允許在一次訪問(wèn)所有的命令行參數(shù)。 $ *和$ @都將相同的行動(dòng),除非它們被括在雙引號(hào)“”。
這兩個(gè)參數(shù)指定的命令行參數(shù),但“$ *”特殊參數(shù)需要整個(gè)列表作為一個(gè)參數(shù)之間用空格和“$ @”特殊參數(shù)需要整個(gè)列表,將其分為不同的參數(shù)。
我們可以寫下面所示的命令行參數(shù)處理數(shù)目不詳?shù)? *$ @特殊參數(shù)的shell腳本:
#!/bin/sh
for TOKEN in $*
do
echo $TOKEN
done
有一個(gè)例子運(yùn)行上面的腳本:
$./test.sh Zara Ali 10 Years Old
Zara
Ali
10
Years
Old
注:在這里 do...done是一種循環(huán),在以后的教程中,我們將涵蓋。
$? 變量表示前一個(gè)命令的退出狀態(tài)。
退出狀態(tài)是一個(gè)數(shù)值,完成后返回的每一個(gè)命令。作為一項(xiàng)規(guī)則,大多數(shù)命令返回,如果他們不成功退出狀態(tài)為0,如果他們是成功的。
一些命令返回其他特殊退出狀態(tài)。例如,一些命令區(qū)分類型的錯(cuò)誤,并且將返回各種退出值取決于特定類型失效。
成功的命令如下面的例子:
$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2
$echo $?
0
$
更多建議: