命令替换指的是将命令的标准输出作为值赋给某个变量,是shell编程中使用非常频繁的功能。
命令替换的格式有两种:一种是反引号(`),一种是$()。例如系统命令date用于获取当前的时间,若将该命令的运行结果保存到变量中,则使用如下:
[root@node1 ~]# date_01=`date`
[root@node1 ~]# date_02=$(date)
[root@node1 ~]# echo $date_01
Sat May 8 18:54:16 CST 2021
[root@node1 ~]# echo $date_02
Sat May 8 18:54:26 CST 2021
若被引用的命令输出有多行,则变量的输出需加引用,若不加引用,则输出的内容中会删除换行符,文件名之间会使用默认的空来填充,即输出的内容只占一行。
[root@node1 ~]# ls=`ls -a`
[root@node1 ~]# echo $ls
. .. add_mius.sh a.txt .bash_history .bash_logout .bash_profile .bashrc b.txt c3pool .cache .cmake .cshrc ejabberd-20.03-0.x86_64.rpm get-docker.sh .gitconfig .git-credentials .history install.sh .mysql_history name.txt newsed.txt .oracle_jre_usage .pearrc .pip .pki .rnd r.txt sed.txt sort.txt split .ssh .tcshrc test uniq.txt
[root@node1 ~]# echo "$ls"
.
..
add_mius.sh
a.txt
.bash_history
.bash_logout
.bash_profile
.bashrc
b.txt
c3pool
.cache
.cmake
.cshrc
ejabberd-20.03-0.x86_64.rpm
get-docker.sh
.gitconfig
.git-credentials
.history
install.sh
.mysql_history
name.txt
newsed.txt
.oracle_jre_usage
.pearrc
.pip
.pki
.rnd
r.txt
sed.txt
sort.txt
split
.ssh
.tcshrc
test
uniq.txt
两个命令需要注意的点是:
- $()支持嵌套,反引号不行
- $()仅在bash shell中有效,而反引号可在多种shell中使用