Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
2  
A Bash-specific discussion can be found in Can a Bash script tell what directory it's stored in? on StackOverflow –  Henk Langeveld Mar 4 at 10:51

2 Answers 2

up vote 8 down vote accepted

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.

share|improve this answer

$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"
share|improve this answer
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) –  Olivier Dulac Mar 4 at 8:36
    
@OlivierDulac This has the benefit of always showing the absolute path. –  Totor Mar 5 at 1:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.