5

I have a shell script in /usr/bin. Let's call it hello.

It contains this:

 echo "I am located in $PWD"
 echo "I am called from this directory: ???"

Running hello from /home/Documents I expect the following output:

 I am located in /usr/bin
 I am called from this directory: /home/Documents

How can I get the directory path where the script is run from?

1

2 Answers 2

8

Can't comment on another answer, so I'm posting here. As said, dirname just reads $0 and takes the directory name, so if you called something like ../../directory/something.sh it does not resolve those dots but just returns ../../directory. Instead of using subshell expansion with cd and pwd, you can use a very smart command readlink that actually resolves not only dotted directories but all symbolic links as well. I therefore suggest

  echo "I am located at $(readlink -e -- "$0")"

You may use another dirname around this to get the directory instead of the file.

6

$PWD was the variable that contains the current directory. To get the directory to the shell script $(dirname -- "$0") can be used.

The content of the script will look like:

echo "I am located in $(dirname -- "$0")"
echo "I am called from this directory: $PWD"
2
  • 2
    another way for the 1st line (so that "./something" will not output only "." ...) : echo "I am located in $(cd "$(dirname "$0")" && pwd)" (don't worry, $(...) will run this in a subshell, so the cd only occurs in that subshell and will not affect the rest of the script, and thus the 2nd line will still work) Mar 4, 2014 at 8:36
  • @OlivierDulac This has the benefit of always showing the absolute path.
    – Totor
    Mar 5, 2014 at 1:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .