Difference between $() and () in Bash

落爺英雄遲暮 提交于 2019-12-10 12:36:51

问题


When I type ls -l $(echo file) output from bracket (which is just simple echo'ing) is taken and passed to external ls -l command. It equals to simple ls -l file.

When I type ls -l (echo file) we have error because one cannot nest () inside external command.

Can someone help me understand the difference between $() and () ?


回答1:


$(cmd) substitutes the result of cmd as a string, whereas (cmd; cmd) run a list of commands in a subprocess.

If you want to put the output of one or more commands into a variable use the $( cmd ) form.

However if you want to run a number of commands and treat them as a single unit use the () form.

The latter is useful when you want to run a set of commands in the background:

(git pull; make clean; make all) &



回答2:


They are different, but there is a mnemonic relationship between them.

(...) is a command that starts a new subshell in which shell commands are run.

$(...) is an expression that starts a new subshell, whose expansion is the standard output produced by the commands it runs.

This is similar to another command/expression pair in bash: ((...)) is an arithmetic statement, while $((...)) is an arithmetic expression.




回答3:


Those are different things.

$() evaluates an expression (executing a command) like `` (backticks)

> (echo ls)
ls

> $(echo ls)
file1  file2

> `echo ls`
file1  file2

> echo $(echo ls)
ls


来源:https://stackoverflow.com/questions/39110485/difference-between-and-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!