So I'm learning some bash and I'm trying to figure out how to get the directory a script is run from. So given that I have my script ~/scripts/bash/myscript
, if I execute my scipt like:
user@localhost ~/dir/I/need/to/run/the/script/from $ ~/scripts/bash/myscript
from within my script, how can I get the directory from which it's being executed, so that I get ~/dir/I/need/to/run/the/script/from
in this case. Shortcuts like:
DIR=`pwd`
DIR="$(cd "$(dirname "$0")" && pwd)"
DIR=`dirname $0`
as far as I can notice, they all assign the path to the script to DIR
, but I'm looking for the path the script was run from.
Any help on this?
Thanks!! :)
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).
In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.
This directory is usually in the $PATH of all users by default. Traditionally, programs that are not installed through a package manager (eg apt ) are stored in the /usr/local/bin directory and those installed by the package manager in /usr/bin .
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 $PWD
variable is probably what you need.
$ cat >/tmp/pwd.bash <<'END'
#!/bin/bash
echo "\$0=$0"
echo "\$PWD=$PWD"
END
$ chmod u+x /tmp/pwd.bash
$ pwd
/home/jackman
$ /tmp/pwd.bash
$0=/tmp/pwd.bash
$PWD=/home/jackman
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With