在 shell 脚本中使用 $() 而不是反引号有什么好处? [英] What is the benefit of using $() instead of backticks in shell scripts?

查看:31
本文介绍了在 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.

    这篇关于在 shell 脚本中使用 $() 而不是反引号有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆