Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get script file path inside script itself when called through sym link

When I need to get path to the script file inside script itself I use something like this:

`dirname $0`

that works file until I call the script through sym link to it. In that case above code prints the location of the link instead the original file.

Is there a way to get the path of the original script file, not the link?

Thanks, Mike

like image 265
Ma99uS Avatar asked May 28 '09 13:05

Ma99uS


2 Answers

if [ -L $0 ] ; then
    DIR=$(dirname $(readlink -f $0)) ;
else
    DIR=$(dirname $0) ;
fi ;
like image 105
dsm Avatar answered Oct 07 '22 08:10

dsm


You really need to read the following BashFAQ article:

  • BashFAQ/028 - How do I determine the location of my script? I want to read some config files from the same place.

The truth is, the $0 hacks are NOT reliable, and they will fail whenever applications are started with a zeroth argument that is not the application's path. For example, login(1) will put a - in front of your application name in $0, causing breakage, and whenever you invoke an application that's in PATH $0 won't contain the path to your application but just the filename, which means you can't extract any location information out of it. There are a LOT more ways in which this can fail.

Bottom line: Don't rely on the hack, the truth is you cannot figure out where your script is, so use a configuration option to set the directory of your config files or whatever you need the script's path for.

like image 35
lhunath Avatar answered Oct 07 '22 10:10

lhunath