22

How may I detect the name of the directory (or better yet the entire path) in which my shell script is run?

1

4 Answers 4

21

what shell? What operating system?

For starters try

man pwd
$PWD
Sign up to request clarification or add additional context in comments.

1 Comment

And if you do want just the directory's name, instead of the full path, read man basename too.
17

This, I believe, is the most portable way:

dir=$(cd -P -- "$(dirname -- "$0")" && pwd -P)

Comments

3

This is not as trivial as it looks like. Check out this question and this

3 Comments

The question is about determining the script execution directory, but your answer is for determining the name / directory of the script file.
@Mat indeed! Must have misunderstood back then. Deleting.
Could you add a little bit more information? See meta.stackexchange.com/questions/8231/…
0

alternative method

pid=$$
path=$(ps -eo pid,args| awk -vp=$pid '$1~p{print $3}')
case "$path" in
    ./* ) pwd;;
    * ) echo $path;;
esac

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.