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.
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.
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, cd
s 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.
Let's break it down:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
${BASH_SOURCE[0]}
: will resolve to the script name as it was called from the command line (you need ${} to access the array cleanly)"$( dirname "${BASH_SOURCE[0]}" )"
: will resolve to the dir part of it
dirname "/foo/bar"
give "/foo""
(quotes) handle the case when you have space in it (both in filename and in path)$(command)
will call the command and return the stdout in a variableThis first part has some limitation. If your script is called through a link, you will receive the dir name of the link, not of the script. That can be fine. But if you want to source another file (let's say a lib), this file is located aside of your real script. To find the real path, you need a bit more:
$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
: will resolve to the real path of your script.How to use it?
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
. "$DIR"/lib.sh
What not to do?
pwd
: This does work only if you always launch your script from it's current folder. This can work for some system script, but usually, you don't do that.