在 shell 脚本中使用 $() 而不是反引号有什么好处?

在 shell 脚本中使用 $() 而不是反引号有什么好处?

问题描述:

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

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

  1. 旧版 Bourne shell 反引号 ``:

var=`command`

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

  • $() 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) 既然特定 命令可能实际上不起作用,我还没有测试该功能.所以,如果你投我反对票,你就忽略了它的意图 :-) 这只是一个关于如何嵌套的说明,而不是一个无错误的生产就绪片段.


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