linux-shell-command substitution and variable substitution

步履不停
Release: 2019-06-18 16:56:51
Original
4320 people have browsed it

linux-shell-command substitution and variable substitution

Command substitution$() ``

Shell 命令替换是指将命令的输出结果赋值给某个变量
Copy after login

There are two ways to complete command substitution in Shell, one is backtick , and the other is The first is $(), and the usage method is as follows:

variable=`commands`
variable=$(commands)
Copy after login

where variable is the variable name and commands is the command to be executed. commands can have only one command or multiple commands, separated by semicolons;

a=`expr 1 + 1`
echo $a
Copy after login

$( ) and ``The difference between

在操作上,这两者都是达到相应的效果,但是建议使用$( ),理由如下:

1.``很容易''搞混乱,尤其对初学者来说。
2.在多层次的复合替换中,``必须要额外的转义字符处理(反斜线),而$( )比较直观。
3.$( )的弊端是,并不是所有的类unix系统都支持这种方式,但反引号是肯定支持的。
Copy after login

Variable substitution${}

变量替换
变量替换可以根据变量的状态(是否为空、是否定义等)来改变它的值

可以使用的变量替换形式:

形式    说明
${var}    变量本来的值
${var:-word}    如果变量 var 为空或已被删除(unset),那么返回 word,但不改变 var 的值。
${var:=word}    如果变量 var 为空或已被删除(unset),那么返回 word,并将 var 的值设置为 word。
${var:?message}    如果变量 var 为空或已被删除(unset),那么将消息 message 送到标准错误输出,可以用来检测变量 var 是否可以被正常赋值。
若此替换出现在Shell脚本中,那么脚本将停止运行。
${var:+word}    如果变量 var 被定义,那么返回 word,但不改变 var 的值。
Copy after login

For more Linux-related technical articles, please Visit the Linux Tutorial column to learn!

The above is the detailed content of linux-shell-command substitution and variable substitution. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template