tags:

views:

148

answers:

4

I'm writing a bash script (extremely unpleasant experience, as always) and I need the current working directory to act sanely. When I run the script from the directory in which it is in, it's fine. However, when I run it from somewhere else, the current working directory is for some reason propagated to the script. This is obviously undesirable. The claimed solutions, e.g. here, don't work; in any case I refuse to believe that it's that complicated to do something so simple.

+5  A: 

BASH FAQ entry #28

Ignacio Vazquez-Abrams
"Are you starting to see how ridiculously complex this problem is becoming? And this is still just the simplistic case where we've made a lot of assumptions about the script not moving and not being piped in!"Jesus Christ, is this saying it's actually impossible? It seems to be. Damn, I wish I could uninstall bash without practical repercussions.
eegg
It's impossible under *all* cases. If you restrict some things then it can be done, but still needs a few hoops.
Ignacio Vazquez-Abrams
@eegg: The correct answer here is to just write your script correctly in a way that doesn't care where it's being run from. This may involve certain assumptions about the running system, but assumptions are testable.
Daenyth
A: 

This script seems to work for me:

#!/bin/bash
mypath=`realpath $0`
cd `dirname $mypath`
pwd

The pwd command line echoes the location of the script as the current working directory no matter where I run it from.

Amardeep
`realpath` is unlikely to be installed everywhere. Which may not matter, depending on the OP's situation.
bstpierre
My system doesn't have `realpath` but it does have `readlink` which seems to be similar.
Dennis Williamson
A: 
#!/bin/bash
cd "$(dirname "$0")"
ndim
A: 

Get the real path to your script

if [ -L $0 ] ; then
    ME=$(readlink $0)
else
    ME=$0
fi
DIR=$(dirname $ME)

(This is answer to the same my question here: http://stackoverflow.com/questions/3373132/get-name-of-directory-wher-script-is-executed)

rodnower