Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" How does that work?

I need to get the path of the script. I can do that using pwd if I am already in the same directory, I searched online and I found this

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

But I don't know how to use that.

like image 438
Anirudh Avatar asked Sep 06 '16 03:09

Anirudh


People also ask

What is CD $( dirname $0?

What is dirname $0 in shell? The dirname $0 command returns the directory where the Bash script file is saved. We can return a relative path or an absolute path. This all depends on how the bash script is called. The $0 parameter contains the name of the shell script.

What is Bash_source in shell script?

BASH_SOURCE. An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}

What does dirname mean in Linux?

dirname is a command in Linux which is used to remove the trailing forward slahes “/” from the NAME and prints the remaining portion. If the argument NAME does not contains the forward slash “/” then it simply prints dot “.”.

How do I find the directory of a script?

pwd can be used to find the current working directory, and dirname to find the directory of a particular file (command that was run, is $0 , so dirname $0 should give you the directory of the current script).


1 Answers

Bash maintains a number of variables including BASH_SOURCE which is an array of source file pathnames.

${} acts as a kind of quoting for variables.

$() acts as a kind of quoting for commands but they're run in their own context.

dirname gives you the path portion of the provided argument.

cd changes the current directory.

pwd gives the current path.

&& is a logical and but is used in this instance for its side effect of running commands one after another.

In summary, that command gets the script's source file pathname, strips it to just the path portion, cds to that path, then uses pwd to return the (effectively) full path of the script. This is assigned to DIR. After all of that, the context is unwound so you end up back in the directory you started at but with an environment variable DIR containing the script's path.

like image 118
Ouroborus Avatar answered Sep 24 '22 00:09

Ouroborus