What is the benefit of using $() instead of backticks in shell scripts?

后端 未结 8 1006
梦谈多话
梦谈多话 2020-11-22 05:05

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

  1. Legacy Bourne shell backticks ``:

    var=`command`
             
    
    
            
8条回答
  •  广开言路
    2020-11-22 05:47

    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)
    

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

提交回复
热议问题