tags:

views:

26

answers:

3

I'm using PWD to get the present working directory. Is there a SED or regex that I can use to, say, get the full path two parents up?

+1  A: 

Why sed or regex? Why not dirname:

parent=`dirname $PWD`
grandparent=`dirname $parent`

Edit:

@Daentyh points out in the comments that apparently $() is preferred over backquotes `` for command substitution in POSIX-compliant shells. I don't have experience with them. More info:

http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_03

So, if this applies to your shell, you can (should?) use:

parent=$(dirname $PWD)
grandparent=$(dirname $parent)
Bert F
Thanks that worked!
Steve
You should use `$()` over `\`\`` since he specified bash.
Daenyth
@Daenyth - true, I was actually thinking of suggesting he retag the question (or allow me to retag it) to `sh` or `shell-scripting` since the question wasn't really `bash` specific. @Steve - what do you think?
Bert F
Even so, `$()` is still POSIX sh. (Not all sh are POSIX though)
Daenyth
Further nag: You should quote PWD as `"$PWD"`, otherwise spaces in a directory name will break you. @Benoit's solution is far simpler though and will work anywhere without trouble. `dirname` is not entirely portable also.
Daenyth
+1  A: 

why not use

"${PWD}/../.."

?

Benoit
A: 

This should work in POSIX shells:

echo ${PWD%/*/*}

which will give you an absolute path rather than a relative one.

Dennis Williamson