Wednesday 23 July 2014

Get the path to the executed sh with $(dirname $0)

Lets imagine that you have an A.sh file, that uses some relatives path from this file. Something like: "../.."
And some times you run A.sh file directly, ans sometimes you call it from another B.sh. And when you cal it from B.sh all relatives paths in A.sh could not work any more.

To make the A.sh properly works in both cases you can use something like:

 $(dirname $0)/../..  

The $0 command should return the path from the A.sh file to the B.sh concatenated with /B.sh (file name of the .sh that i called from an other .sh file)

And dirname simply truncates everything after the last slash with the last slack itself. I our case it will truncate /B.sh. If B.sh will be called directly, $0 will return ./ and dirname will do nothing, so everything will work in this case, too.

No comments:

Post a Comment