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