Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash scripting: how to find the absolute path of "symlink/.."?

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.

like image 295
dagnelies Avatar asked Jun 07 '11 15:06

dagnelies


People also ask

How do I find the path of a symbolic link?

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.

How do I find absolute path in Bash?

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.

How do I find the absolute path of a file?

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.

How do I find absolute path in Linux?

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.


2 Answers

Try this:

basename $(dirname $(dirname $0))

or perhaps just

$(dirname $(dirname $0))

It is unclear if you want parent alone or its full path.

like image 136
jlliagre Avatar answered Nov 15 '22 17:11

jlliagre


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

like image 21
Op De Cirkel Avatar answered Nov 15 '22 17:11

Op De Cirkel