Bash 中 $() 和 () 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39110485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between $() and () in Bash
提问by run4gnu
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
.
当我ls -l $(echo file)
从括号中输入输出(这只是简单的回显)并传递给外部ls -l
命令时。它等于简单ls -l file
。
When I type ls -l (echo file)
we have error because one cannot nest ()
inside external command.
当我输入时,ls -l (echo file)
我们有错误,因为不能嵌套()
在外部命令中。
Can someone help me understand the difference between $()
and ()
?
有人可以帮助我理解之间的差异$()
和()
?
回答by Barry Scott
$(cmd)
substitutes the result of cmd
as a string, whereas (cmd; cmd)
run a list of commands in a subprocess.
$(cmd)
将结果替换cmd
为字符串,而(cmd; cmd)
在子进程中运行命令列表。
If you want to put the output of one or more commands into a variable use the $( cmd ) form.
如果要将一个或多个命令的输出放入变量中,请使用 $( cmd ) 形式。
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) &
回答by chenchuk
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
回答by chepner
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.
(...)
是一个命令,它启动一个新的子 shell,在其中运行 shell 命令。
$(...)
is an expression that starts a new subshell, whose expansion is the standard output produced by the commands it runs.
$(...)
是一个启动新子shell的表达式,其扩展是它运行的命令产生的标准输出。
This is similar to another command/expression pair in bash
: ((...))
is an arithmetic statement, while $((...))
is an arithmetic expression.
这类似于另一个命令/表达式对bash
:((...))
是算术语句,而$((...))
是算术表达式。