Introduction
As a Linux user, you're probably no stranger to the Bash shell. Bash is the default shell on most Linux distributions, and for good reason—it's incredibly versatile and can be used for everything from simple tasks like viewing files to more complex functions like writing scripts.
One common task that Bash scripts often need to perform is finding the directory path of the script itself. This can be useful for creating absolute paths (which are less susceptible to breaking when the script is moved) or for finding other files in the same directory as the script. Fortunately, you can assign a Bash variable that makes this task a breeze, and works in almost all cases.
Using a DIR
Variable
In Bash, you can go ahead and create DIR
variable contains the directory path of the current script.
This is different from $PWD
(which contains the current working directory) in that DIR
always contains an absolute path, whereas $PWD
may be relative. For example, if my current working directory is /home/user/Documents
and I have a script located at /home/user/Documents/myscript.sh
, DIR
would contain /home/user/Documents
while $PWD
would contain /home/user/Documents
(assuming myscript.sh didn't change the working directory).
One popular way to do this is to make use of built-ins like dirname
:
DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
To use DIR
, simply insert it wherever you need the directory path in your script. For example, let's say I have a script located at /home/user/Scripts/myscript.sh
that needs to read a file located in the same directory. I could use DIR
to construct an absolute path to that file like so:
FILE=/home/user/Scripts/$(DIR)/myfile.txt
Alternatively, you could use it to construct a relative path like this:
FILE=$(DIR)/myfile.txt
You can save useful shell shortcuts like this, and a whole lot more, with Cased. If you're interested and want to learn more schedule a demo or visit our documentation.