📜  Unix / Linux-Shell替代

📅  最后修改于: 2020-10-31 14:54:26             🧑  作者: Mango


什么是替代?

当Shell遇到包含一个或多个特殊字符的表达式时,它将执行替换。

在此,变量的打印值由其值代替。同时, “ \ n”被换行-

#!/bin/sh

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

您将收到以下结果。在这里, -e选项启用反斜杠转义的解释。

Value of a is 10

以下是不带-e选项的结果-

Value of a is 10\n

以下可在echo命令中使用的转义序列-

Sr.No. Escape & Description
1

\\

backslash

2

\a

alert (BEL)

3

\b

backspace

4

\c

suppress trailing newline

5

\f

form feed

6

\n

new line

7

\r

carriage return

8

\t

horizontal tab

9

\v

vertical tab

您可以使用-E选项禁用反斜杠转义的解释(默认)。

您可以使用-n选项禁用插入新行。

命令替换

命令替换是一种机制,外壳程序通过该机制执行给定的命令集,然后替换其输出来代替命令。

句法

当命令给定为-时执行命令替换

`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程序员可以根据变量的状态来操作变量的值。

下表是所有可能的替代方法-

Sr.No. Form & Description
1

${var}

Substitute the value of var.

2

${var:-word}

If var is null or unset, word is substituted for var. The value of var does not change.

3

${var:=word}

If var is null or unset, var is set to the value of word.

4

${var:?message}

If var is null or unset, message is printed to standard error. This checks that variables are set correctly.

5

${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