0

Lets say I have a script called foo in some folder and a script called bar in the same folder. Say foo looks like this:

./bar

Now if I call ./foo, this will work fine, but if I am in another folder and call somefolder/foo, it will fail.

How can I get this to the point where ./bar is interpreted from the directory that foo is in?

Martin Ueding
  • 8,245
  • 6
  • 46
  • 92

2 Answers2

2

foo could look like this:

cd "$(dirname "$0")"
./bar
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • The problem is that this will mess up all other arguments that are paths if you change the directory. But combining both statements gives the desired effect. – Martin Ueding Jul 31 '11 at 18:03
1

Answered pretty exhaustively for bash and other shells in:

Getting the source directory of a Bash script from within

Community
  • 1
  • 1
iandotkelly
  • 9,024
  • 8
  • 48
  • 67
  • Welcome to Stack Overflow. Don't answer a question with just a link, please read [how-to-answer]. When you see a question that's an exact duplicate of the earlier question, click on the `flag` button on the question, select `it doesn't belong here` then `exact duplicate` and enter the link to the earlier question. Also leave a comment to let others now (the flag remains invisible until a moderator has acted on it). – Gilles 'SO- stop being evil' Jul 16 '11 at 09:33
  • Noted. It may be possible that I did not have enough reputation to flag this - as you can tell I am new. – iandotkelly Jul 16 '11 at 13:36