deuteriumoxide
deuteriumoxide

Reputation: 193

Get Directory Bash Script is Called From if it's a Sym Link

Let's say I have a bash script called program stored in /home/user/program. But then I create a sym link to the bash script using ln -s /home/user/program /usr/bin/program. Then I cd /usr/home/anotherdirectory and then run program. How do I get the bash script to print /usr/home/anotherdirectory to tell me where it was called from?

I tried echo $PWD and it only printed out /usr/bin

Upvotes: 2

Views: 2570

Answers (1)

Cyrus
Cyrus

Reputation: 88553

This should do the job in your script:

dirname $(readlink -e "$0")

From man readlink:

-e:canonicalize by following every symlink in every component of the given name recursively, all components must exist

Upvotes: 2

Related Questions