Saturday, December 3, 2011

Programmers' Advent Calendar: #1 Finding a path to a bash script

I have decided to start this series, for the 24 days of christmas, I will dedicate a post each day to tell you about a little thing you might not have known. I will try to stick to small examples or one liners most of them time. However, some biggers stuff will be too good to miss. This is the first post of the Series.

Often enough, you are writing a bash script and you want to find out where is your script. Here is a reliable and repeatable way to find the directory where your path resides.

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

However, if your script changes directories before calling this, it will get the wrong value. Now let me explain how the script works. BASH_SOURCE[0] will return the relative path of the script from the directory where the script was called. dirname will remove the script name from that. Which at the beginning of the script is the same as pwd. If we go to that directory then we are at the same dir as the script. Executing pwd there will give us the absolute path. And this is what we store in DIR.

Come back tomorrow for another post :).

1 comment:

Mujtaba said...

Thanks a lot...
I was exactly looking for this thing..:)