命令替换
命令替换就是在SHELL 内嵌套多条命令,一次性执行得到结果。
一层Shell嵌套
echo whoami
whoami
echo 'whoami'
whoami
echo "whoami"
whoami
echo `whoami`
root
echo $(whoami)
root
echo "hello,`whoami`"
hello,root
echo "hello,$(whoami)"
hello,root
二层Shell嵌套
编写test.tx文件,里面只有ls命令
shell> echo `cat ./test.txt` | sed -s "s;$; -l;"
shell> ls -l
shell> $(echo `cat ./test.txt` | sed -s "s;$; -l;")
shell> 打印当前目录下所有文件,上面的语句其实转化为$(ls -l)
之前在简单 SHELL 一层嵌套中说了嵌套还有另一种。那为什么不使用` `进行嵌套。
- ` `不支持命令嵌套执行
- 强制执行。也只能认出第一组,其余按照空格作为间隔各个执行 或 按照管道符(含)直到末尾执行
- 比较陈旧。容易与“单引号”混淆。
- 已有替代品。
$(...)
格式受到POSIX标准支持,也利于嵌套。 $()
可以多层嵌套类似$($($()))