有两种方法可以捕获命令行的输出bash
:
-
旧版 Bourne shell 反引号``
:
var=`command`
-
$()
语法(据我所知,这是 Bash 特定的,或者至少不被非 POSIX 旧 shell(如原始 Bourne)支持)
var=$(command)
与反引号相比,使用第二种语法有什么好处吗?或者两者完全100%等同吗?
最主要的是有能力nest它们是命令中的命令,而不会失去理智试图弄清楚某种形式的转义是否适用于反引号。
一个例子,虽然有些做作:
deps=$(find /dir -name $(ls -1tr 201112[0-9][0-9]*.txt | tail -1l) -print)
which will give you a list of all files in the /dir
directory tree which have the same name as the earliest dated text file from December 2011 (a).
另一个例子是获取父目录的名称(而不是完整路径):
pax> cd /home/pax/xyzzy/plugh
pax> parent=$(basename $(dirname $PWD))
pax> echo $parent
xyzzy
(a) Now that specific command may not actually work, I haven't tested the functionality. So, if you vote me down for it, you've lost sight of the intent :-) It's meant just as an illustration as to how you can nest, not as a bug-free production-ready snippet.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)