What does it mean in shell when we put a command inside dollar sign and parentheses: $(command)

你离开我真会死。 提交于 2019-11-26 12:06:32

问题


I just want to understand following line of code in shell. It is used to get the current working directory. I am aware that $(variable) name return the value inside the variable name, but what is $(command) supposed to return? Does it return the value after executing the command? In that case, we can use ` to execute the command.

CWD=\"$(cd \"$(dirname $0)\"; pwd)\"

Same output can be taken from the following line of code also in different version of shell

DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"

I am unable to understand the meaning of $(cd.. and $(dirname.

Could anybody help me to figure out how this command get executed?


回答1:


Usage of the $ like ${HOME} gives the value of HOME. Usage of the $ like $(echo foo) means run whatever is inside the parentheses in a subshell and return that as the value. In my example, you would get foo since echo will write foo to standard out




回答2:


DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

Could anybody help me to figure out how this command get executed?

Let's look at different parts of the command. BASH_SOURCE is a bash array variable containing source filenames. So "${BASH_SOURCE[0]}" would return you the name of the script file.

dirname is a utility provided by GNU coreutils that remove the last component from the filename. Thus if you execute your script by saying bash foo, "$( dirname "${BASH_SOURCE[0]}" )" would return .. If you said bash ../foo, it'd return ..; for bash /some/path/foo it'd return /some/path.

Finally, the entire command "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" gets the absolute directory containing the script being invoked.

$(...) allows command substitution, i.e. allows the output of a command to replace the command itself and can be nested.



来源:https://stackoverflow.com/questions/17984958/what-does-it-mean-in-shell-when-we-put-a-command-inside-dollar-sign-and-parenthe

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