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.
views:
148answers:
4"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
2010-07-28 00:58:07
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
2010-07-28 01:02:15
@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
2010-07-28 01:33:18
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
2010-07-28 00:59:56
`realpath` is unlikely to be installed everywhere. Which may not matter, depending on the OP's situation.
bstpierre
2010-07-28 03:42:18
My system doesn't have `realpath` but it does have `readlink` which seems to be similar.
Dennis Williamson
2010-07-28 03:46:57
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
2010-07-30 19:08:59