1

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.

3

1 Answer 1

1

This should do the job in your script:

dir="$(readlink /proc/$PPID/cwd)" 
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Indeed, the script directory resolves to the user's home when launched from cron
@GordonDavisson: Thank you for the hints. Yes, the scope is limited.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.