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
2010-09-24 19:08:19
Thanks that worked!
Steve
2010-09-24 19:15:48
You should use `$()` over `\`\`` since he specified bash.
Daenyth
2010-09-24 19:17:42
@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
2010-09-24 19:33:57
Even so, `$()` is still POSIX sh. (Not all sh are POSIX though)
Daenyth
2010-09-24 19:37:54
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
2010-09-24 19:52:01
A:
This should work in POSIX shells:
echo ${PWD%/*/*}
which will give you an absolute path rather than a relative one.
Dennis Williamson
2010-09-24 20:14:07