21

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
1
  • And if you do want just the directory's name, instead of the full path, read man basename too.
    – Roger Pate
    Commented Nov 30, 2009 at 2:46
17

This, I believe, is the most portable way:

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

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

3
  • The question is about determining the script execution directory, but your answer is for determining the name / directory of the script file.
    – Mat Gessel
    Commented Mar 12, 2017 at 19:44
  • @Mat indeed! Must have misunderstood back then. Deleting.
    – Pekka
    Commented Mar 12, 2017 at 21:22
  • Could you add a little bit more information? See meta.stackexchange.com/questions/8231/…
    – Marco
    Commented May 5, 2018 at 23:02
0

alternative method

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

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