up vote 1 down vote favorite
share [g+] share [fb]

In /usr/local/bin I have a 'ln -s' to /usr/local/foo/bash.script, and in this latter script I want to know the current /usr/local/foo directory, so that I can run a secondary script from that folder.

Now, I tried dirname $0, but that gives me the /usr/local/bin folder instead. What should I be using in the bash.script to get the /usr/local/foo folder?

link|improve this question
feedback

1 Answer

up vote 5 down vote accepted

try readlink, e.g.

d=$0

while readlink $d >/dev/null; do
  d=`readlink $d`
done
echo $d

EDIT:

I am not sure if that works on other Unix OS, but if you are on linux the above can be simplified by using

d=`readlink -f $0`

echo $d

see

readlink --help
link|improve this answer
Thanx for the pointers! I still need to combine with dirname, and I saw the readlink -f, doing the above in one command ... any idea on how portable that is? – Egon Willighagen Jan 31 '10 at 12:03
@Egon: -f worked for on cygwin (on Win-7-64bit) too. But it doesn't work on MacOS. – Vokuhila-Oliba Jan 31 '10 at 12:10
Ah, well, that's good enough for my needs, because it is part of a script only for Linux :) thanx! – Egon Willighagen Jan 31 '10 at 12:13
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.