Shell 特殊變數

以前的教程中說過有關在變數名中使用某些非字母數字字元。這是因為這些字元中使用特殊的Unix變數的名稱。這些變數被保留用於特定功能。

例如,$字元表示進程ID號,或PID,在當前shell:

$echo $$

上面的命令將寫入在當前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.

命令行參數:

該命令行參數 $1, $2, $3,...$9 是位置參數,與0美元指向實際的命令,程式,shell腳本,函數和 $1, $2, $3,...$9 作為參數的命令。

下麵的腳本使用命令行相關的各種特殊變數:

#!/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 : $#"

下麵是一個示例運行上面的腳本:

$./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

特殊參數$ *和$ @:

有特殊的參數,允許在一次訪問所有的命令行參數。 $ *和$ @都將相同的行動,除非它們被括在雙引號“”。

這兩個參數指定的命令行參數,但“$ *”特殊參數需要整個列表作為一個參數之間用空格和“$ @”特殊參數需要整個列表,將其分為不同的參數。

我們可以寫下面所示的命令行參數處理數目不詳的$ *$ @特殊參數的shell腳本:

#!/bin/sh

for TOKEN in $*
do
   echo $TOKEN
done

有一個例子運行上面的腳本:

$./test.sh Zara Ali 10 Years Old
Zara
Ali
10
Years
Old

注:在這裏 do...done是一種迴圈,在以後的教學中,我們將涵蓋。

退出狀態:

 $? 變數表示前一個命令的退出狀態。

退出狀態是一個數值,完成後返回的每一個命令。作為一項規則,大多數命令返回,如果他們不成功退出狀態為0,如果他們是成功的。

一些命令返回其他特殊退出狀態。例如,一些命令區分類型的錯誤,並且將返回各種退出值取決於特定類型失效。

成功的命令如下面的例子:

$./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
$

上一篇: Shell 使用Shell變數 下一篇: Shell 數組/Arrays