Programming and Scripting :: cd into dirname of linked script
One situation I occasionally run into with a bash wrapper script is that I need to cd into the directory that contains the wrapper script before running the wrapped application. This is easy enough to do with cd `dirname $0` if the wrapper is called directly. However, if the wrapper is linked into your $PATH and you call that link instead the output of dirname $0 will be the directory containing the link instead of the directory contaning the wrapper.
I've come up with one way to deal with this, but i'm not sure it's universal, and it doesn't work for hard links:
Code Sample
CHECK_LINK=`ls -l $0 | grep ^l` if [ -n "$CHECK_LINK" ];then REAL_FILE=`ls -l $0 | awk '{print $NF}'` cd `dirname $REAL_FILE` else cd `dirname $0` fi
Can anyone recommend a more effective or more efficient way to do this? Even if it doesn't work for hard links it's no big deal, but i'm concerned mostly with efficiency...hopefully accomplishing the same task with fewer commands.
Thanks.Can you pipe the output of "whereis" into your script?I'm not sure what you're suggesting. As far as I know, the whereis command works only with PATH and MANPATH, so it wouldn't apply if the script is in a directory that is not in $PATH. Even using the absolute path to the wrapper as an argument to whereis still returns only files in $PATH and $MANPATH. It also returns multiple paths, so it would somehow need to know which path is needed.
The thing I'm really attempting to achieve is the ability to have the wrapper cd into its own directory no matter where it is located or how the user has started the script (whether it's directly run, or from a symlink, or from an alias, or some other method), and be able to use that same piece of script any time i need to reuse this behavior in other wrappers. The script above does almost exactly what I want, but it uses something like 6 or 7 commands. The way I see it, the more programs that are required to accomplish a single task, the less portable it may be.
So this does work, but I was just looking for a way to make it more compact and portable.Is there a potential "gotcha" if your symlink points to a second symlink and then the second symlink points to the real file location?
You might need a looping symbolic link check, like this guy has done for the beginning of his script:
http://cvs.sourceforge.net/viewcvs.py/gmod/apollo/bin/apollo?rev=1.42That's exactly the sort of thing that I didn't consider, and was hoping someone would notice =o) At this time i have no idea what this script is, since I just want to apply sleep to myself now...but i've saved it for viewing tomorrow. It looks like i might end up with more code rather than less, but i guess if it makes it more portable then it's better in the long run.