在外壳程序脚本中使用$()代替反引号有什么好处? [英] What is the benefit of using $() instead of backticks in shell scripts?

查看:84
本文介绍了在外壳程序脚本中使用$()代替反引号有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种方法可以捕获 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)
    

    这将为您提供<$ c $中所有文件的列表c> / 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.

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

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