Shell 特殊變量

2021-08-31 09:19 更新

以前的教程中說過有關(guān)在變量名中使用某些非字母數(shù)字字符。這是因為這些字符中使用特殊的Unix變量的名稱。這些變量被保留用于特定功能。

例如,$字符表示進程ID號,或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ù):

該命令行參數(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 : $#"

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

$./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ù)$ *和$ @:

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

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

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

#!/bin/sh

for TOKEN in $*
do
   echo $TOKEN
done

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

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

注:在這里 do...done是一種循環(huán),在以后的教程中,我們將涵蓋。

退出狀態(tài):

 $? 變量表示前一個命令的退出狀態(tài)。

退出狀態(tài)是一個數(shù)值,完成后返回的每一個命令。作為一項規(guī)則,大多數(shù)命令返回,如果他們不成功退出狀態(tài)為0,如果他們是成功的。

一些命令返回其他特殊退出狀態(tài)。例如,一些命令區(qū)分類型的錯誤,并且將返回各種退出值取決于特定類型失效。

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

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

 


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號