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.
ls command to find a symbolic link in UNIX systems If you combine the output of the ls command with grep and use a regular expression to find all entries which start with a small L then you can easily find all soft links on any directories.
In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.
You can determine the absolute path of any file in Windows by right-clicking a file and then clicking Properties. In the file properties first look at the "Location:" which is the path to the file.
The pwd command prints the current/working directory, telling where you are currently located in the filesystem. This command comes to your rescue when you get lost in the filesystem, and always prints out the absolute path.
Try this:
basename $(dirname $(dirname $0))
or perhaps just
$(dirname $(dirname $0))
It is unclear if you want parent
alone or its full path.
I would recommend
1) use pwd -P
which will always give you the physical path, and then navigate with relative path to the other palce This is most safe.
2) use pwd -L
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With