21

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

goe
  • 5,207
  • 14
  • 45
  • 49
  • For Bash, see: [Getting the source directory of a Bash script from within](https://stackoverflow.com/q/59895/55075). – kenorb Jul 19 '17 at 18:39

4 Answers4

21

what shell? What operating system?

For starters try

man pwd
$PWD
Anycorn
  • 50,217
  • 42
  • 167
  • 261
  • And if you do want just the directory's name, instead of the full path, read man basename too. –  Nov 30 '09 at 02:46
17

This, I believe, is the most portable way:

dir=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
3

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

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • The question is about determining the script execution directory, but your answer is for determining the name / directory of the script file. – Mat Gessel Mar 12 '17 at 19:44
  • @Mat indeed! Must have misunderstood back then. Deleting. – Pekka Mar 12 '17 at 21:22
  • Could you add a little bit more information? See https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers – Marco May 05 '18 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
ghostdog74
  • 327,991
  • 56
  • 259
  • 343