What does this mean in the shell when we put the command in the dollar sign and parentheses: $ (command)

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

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

The same conclusion can be taken from the next line of code also in another version of the shell

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

I can not understand the values โ€‹โ€‹of $(cd.. and $(dirname .

Can someone help me figure out how this command is executed?

+58
bash shell terminal sh ksh
Aug 01 '13 at 3:49
source share
2 answers

Using $ as ${HOME} gives a HOME value. Using $ as $(echo foo) means starting everything that is inside the parentheses in the subshell and returning this value. In my example, you will get foo , since echo will write foo to the standard

+61
Aug 01 '13 at 3:53
source share
 DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 

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

Let's look at the different parts of the team. BASH_SOURCE is a bash array variable containing the original file names. Thus, "${BASH_SOURCE[0]}" will return the script file name to you.

dirname is a GNU coreutils utility that removes the last component from a file name. That way, if you execute the script by saying bash foo , "$( dirname "${BASH_SOURCE[0]}" )" will return . . If you said bash ../foo , it would return .. ; for bash /some/path/foo it will return /some/path .

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

$(...)

+15
Aug 01 '13 at 5:09 on
source share



All Articles