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.
parent/scripts/hello.sh
to call the script. – Iasgeneric
is hello's parent directory, that's why all the tools you use give you that. Ifparent/scripts
is not visible in$0
, you'll not get it. On linux,cd
to parent/scripts and dols -l /proc/$$
to see what the OS knows about where you are. – Ontologismpwd
if you are calling it within one of the subdirectories using a relative path. I just have the feeling that you have to manually handle several different cases and that you have to resolve the path using regular expressions ...which I personally think is fairly ugly ...just to get the parent. – Roomette