1

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?

1 Answer 1

5

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
3
  • 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? Jan 31, 2010 at 12:03
  • @Egon: -f worked for on cygwin (on Win-7-64bit) too. But it doesn't work on MacOS. Jan 31, 2010 at 12:10
  • Ah, well, that's good enough for my needs, because it is part of a script only for Linux :) thanx! Jan 31, 2010 at 12:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .