On Tue, Jul 19, 2011 at 12:10:52PM +0100, Brett Parker wrote:
On 19 Jul 11:49, Chris G wrote:
I need to find what the relative directory (relative to $HOME that is) within a bash script and, at the moment, I can only see rather messy ways of doing it.
To go into more detail I want a way to generate a string of the form ~/subdir1/subdir2 when a script is run from ~/subdir1/subdir2.
The best I can come up with at the moment is to get the full path to the current directory using pwd and then to remove $HOME from that string using sed, e.g.:-
fullpath=`pwd` relpath=`echo $fullpath | sed s#$HOME#~#`
Actually that's not quite as nasty a I thought, but it still feels like there should be a neater way. (I haven't tried it so there may well be issues with quoting etc. but you can see the idea)
Erm, well, for a start, assuming bash, you know that you're actually in $PWD so there's no need for the call to pwd.
Good point, I'd forgotten about $PWD.
For seconds, your relpath isn't a relpath, it's still an absolute path, because ~ expands to $HOME.
Well, yes, but you understood what I wanted. What I'm actually doing is managing some files on a number of different logins on a hosting service so I want to be able to do something to '~/subdir1/subdir2/filexxx' in several different logins.
Now, to keep it all in bash and not do all this messing about:
relpath=${PWD#$HOME}
That's the bit I thoughto should be possible, I'm not very well up in bash string manipulations.
if [ "x$relpath" != "x$PWD" ]; then relpath="~$relpath" fi
Actually I'd already hit this issue, fortunately '//' in a path does no harm!
The first bit removes a prefix that matches $HOME. The if statement checks to see if that has done anything (you might not be running things from $HOME) and the bit in the middle prefixes it with a ~ if you have.
If you actually want to get the relative path of the script and you weren't in the same directory as it when it started then you do:
scriptpath=$(readlink -f "$0") relpath=${scriptpath#$HOME} if [ "x$relpath" != "x$scriptpath" ]; then relpath="~$relpath" fi
No, it was the $PWD I wanted, not the script's directory
Hope that helps,
Brilliant, yes, thank you. My horrible sed'ism worked but I much prefer elegant solutions where they're possible.