0

Is there a way to get the script directory regardless of change in current directory that occurred during script execution.

echo $(dirname "$(readlink -f "$0")")
cd /tmp
echo $(dirname "$(readlink -f "$0")")
/home/user/test
/tmp

In the example above, I need /home/user/test both times, without storing it to a variable.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Sergei Rodionov
  • 4,079
  • 6
  • 27
  • 44
  • Why not use a variable? – mouviciel Mar 13 '21 at 07:59
  • Yes, that would be one method, and I use it now, but perhaps there is another way. – Sergei Rodionov Mar 13 '21 at 08:07
  • That's actually difficult to do in all cases; see ["How can I get the source directory of a Bash script from within the script itself?"](https://stackoverflow.com/questions/59895/how-can-i-get-the-source-directory-of-a-bash-script-from-within-the-script-itsel) and [BashFAQ #28: "How do I determine the location of my script? I want to read some config files from the same place."](http://mywiki.wooledge.org/BashFAQ/028) – Gordon Davisson Mar 13 '21 at 10:24

1 Answers1

1

This should do the job in your script:

dir="$(readlink /proc/$PPID/cwd)"
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 1
    This only works if the script was run from the same directory the script itself is in, *and* it hasn't been backgrounded and the parent process changed directories, *and* you're on a system that has /proc. – Gordon Davisson Mar 13 '21 at 10:27
  • Indeed, the script directory resolves to the user's home when launched from cron – Sergei Rodionov Mar 13 '21 at 12:17
  • @GordonDavisson: Thank you for the hints. Yes, the scope is limited. – Cyrus Mar 13 '21 at 18:09