简体   繁体   English

Bash 中 $() 和 () 的区别

[英]Difference between $() and () in Bash

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.当我输入ls -l $(echo file)括号中的输出(这只是简单的 echo'ing)并传递给外部ls -l命令时。 It equals to simple ls -l file .它等于简单的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 () ?有人能帮我理解$()()之间的区别吗?

$(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) &

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另一个命令/表达式对: ((...))是一个算术语句,而$((...))是一个算术表达式。

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

() is also used to create array in bash. ()也用于在 bash 中创建数组。 See man bash :参见man bash

Arrays are assigned to using compound assignments of the form name=(value1 ... valuen), where each value is of the form [subscript]=string.数组被分配为使用名称=(value1 ... valuen) 形式的复合赋值,其中每个值的形式为 [下标]=string。

$ arr=(a b c 'd f' e)
$ declare -p arr 
declare -a arr=([0]="a" [1]="b" [2]="c" [3]="d f" [4]="e")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM