1

I want to execute statements like (shell is bash)

/# source /workspace/scripts/script.sh
/workspace/scripts# source script.sh

Inside the script.sh I want to get its own location. (script.sh wont be in the PATH variable)

I could do this using readlink -f $0 when run the script, but the same doesnt work when I source it.

I dont want the solution to be dependent on where I run the source command from. (otherwise pwd would have been enough)

Is this possible?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Schu
  • 1,124
  • 3
  • 11
  • 23

2 Answers2

4

It is not possible to find the location reliably in 100% of all cases.
If you use bash your best bet is $BASH_SOURCE variable.
This link is very helpful on this topic.

c00kiemon5ter
  • 16,994
  • 7
  • 46
  • 48
  • BASH_SOURCE did the trick. Thank you. (Using the code from http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in?page=1&tab=active#tab-top) – Schu May 01 '12 at 19:53
0

Since script.sh is in your path, you should be able to get it's full path using which. So, in the script, if $0 isn't a full path, you can do which $0.

carabiner$ cat ~/bin/test.sh
#!/bin/sh

echo test - $0 $1
which $0

carabiner$ source test.sh
test - test.sh
test.sh is /home/zigdon/bin/test.sh
zigdon
  • 14,573
  • 6
  • 35
  • 54