Given two files:
generic/scripts/hello.sh parent/scripts -> generic/scripts
Upon calling parent/scripts/hello.sh
from any location, I would like (in the script) to find the full path of the parent directory. In this case parent
.
The main issue is that parent/scripts/..
refers to generic
in unix. On the other hand, everything involving regexes is not generic and may be error prone.
Solutions that don’t work:
`dirname $0`/.. realpath `dirname $0`/.. readlink -f `dirname $0`/.. `cd *something*/..; pwd` `perl ... abs_path(...)`
All these will point to generic
and not parent
because of the symbolic link.
Everything involving regular expressions are not adaptable/generic, may fail for more complexes paths. There might be other ..
and symlinks in the path, you want the grand-parent, it’s a directory name involving ..
, you call it via $PATH…
Moreover, I would like it to work in any case, even when it is called via $PATH
.
Any simple safe solution for this simple problem? I mean it’s just getting the parent directory after all!
What I used:
dir=$( dirname $( cd `dirname $0` >/dev/null; pwd ) )
Dunno if it is perfect but it seems to behave as expected.
Advertisement
Answer
Try this:
basename $(dirname $(dirname $0))
or perhaps just
$(dirname $(dirname $0))
It is unclear if you want parent
alone or its full path.