在外壳程序脚本中使用$()代替反引号有什么好处?

在外壳程序脚本中使用$()代替反引号有什么好处?

问题描述:

有两种方法可以捕获 bash 中的命令行输出:

There are two ways to capture the output of command line in bash:


  1. 旧版Bourne贝壳反引号``

 var=`command`


  • $()语法(据我所知,它是特定于Bash的,或者至少不受非POSIX旧shell(例如原始Bourne)支持)

  • $() syntax (which as far as I know is Bash specific, or at least not supported by non-POSIX old shells like original Bourne)

     var=$(command)
    


  • 与反引号相比,使用第二种语法有什么好处?还是两个完全等于100%?

    Is there any benefit to using the second syntax compared to backticks? Or are the two fully 100% equivalent?

    主要解决方案是嵌套的能力,命令内的命令,而又不失理智地尝试找出某种形式的转义是否可以在反引号上起作用。

    The major one is the ability to nest them, commands within commands, without losing your sanity trying to figure out if some form of escaping will work on the backticks.

    一个示例,尽管有些人为:

    An example, though somewhat contrived:

    deps=$(find /dir -name $(ls -1tr 201112[0-9][0-9]*.txt | tail -1l) -print)
    

    这将为您提供 / dir 目录树,其名称与2011年12月以来最早的带有日期的文本文件同名(a)

    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).

    另一个例子是获取父目录的名称(而不是完整路径)。

    Another example would be something like getting the name (not the full path) of the parent directory:

    pax> cd /home/pax/xyzzy/plugh
    pax> parent=$(basename $(dirname $PWD))
    pax> echo $parent
    xyzzy
    






    (a)既然 specific 命令可能实际上不起作用,我尚未测试该功能。因此,如果您不赞成我,那么您就没有意识到它的意图了:-)这只是为了说明如何嵌套,而不是将其作为无错误的可立即投入生产的代码段。


    (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.