Shell 替代


替代是什麼?

Shell當它遇到一個表示式,其中包含一個或多個特殊字元進行替代。

例子:

下面的例子,同時使列印取代的其值的變數的值。同時“ ”是一個新行取代:

#!/bin/sh

a=10
echo -e "Value of a is $a 
"

這將產生下面的結果。這裡-e選項可以解釋反斜槓跳脫。

Value of a is 10

下面是結果沒有-e選項:

Value of a is 10

這裡echo命令可以用在以下跳脫序列:

跳脫 描述
backslash
a alert (BEL)
 backspace
c suppress trailing newline
f form feed
new line
carriage return
horizontal tab
v vertical tab

可以使用-E選項禁用解釋反斜槓跳脫(預設)。

您可以使用-n選項來禁用插入新行。

命令替換:

命令替換shell執行的機制,一組給定的命令,然後替代它們的輸出在命令。

語法

執行命令替換的命令時,被給定為:

`command`

當執行命令替換,確保您使用的是反引號,不是單引號字元。

例子:

命令替換一般是用一個命令的輸出分配給一個變數。下面的例子演示命令替換:

#!/bin/sh

DATE=`date`
echo "Date is $DATE"

USERS=`who | wc -l`
echo "Logged in user are $USERS"

UP=`date ; uptime`
echo "Uptime is $UP"

這將產生以下結果:

Date is Thu Jul  2 03:59:57 MST 2009
Logged in user are 1
Uptime is Thu Jul  2 03:59:57 MST 2009
03:59:57 up 20 days, 14:03,  1 user,  load avg: 0.13, 0.07, 0.15

變數替代:

變數替換可使Shell程式員操縱變數的值,根據其狀態。

這裡是所有可能的替換如下表:

格式 描述
${var} Substitue the value of var.
${var:-word} If var is null or unset, word is substituted for var. The value of var does not change.
${var:=word} If var is null or unset, var is set to the value of word.
${var:?message} If var is null or unset, message is printed to standard error. This checks that variables are set correctly.
${var:+word} If var is set, word is substituted for var. The value of var does not change.

例子:

下面的例子顯示各種狀態,上述替代:

#!/bin/sh

echo ${var:-"Variable is not set"}
echo "1 - Value of var is ${var}"

echo ${var:="Variable is not set"}
echo "2 - Value of var is ${var}"

unset var
echo ${var:+"This is default value"}
echo "3 - Value of var is $var"

var="Prefix"
echo ${var:+"This is default value"}
echo "4 - Value of var is $var"

echo ${var:?"Print this message"}
echo "5 - Value of var is ${var}"

這將產生以下結果:

Variable is not set
1 - Value of var is
Variable is not set
2 - Value of var is Variable is not set

3 - Value of var is
This is default value
4 - Value of var is Prefix
Prefix
5 - Value of var is Prefix