Schu
Schu

Reputation: 1164

Get location of "source"ed script

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?

Upvotes: 1

Views: 291

Answers (2)

zigdon
zigdon

Reputation: 15063

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

Upvotes: 0

c00kiemon5ter
c00kiemon5ter

Reputation: 17614

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.

Upvotes: 4

Related Questions