Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: how to get real path of a symlink? [duplicate]

Tags:

bash

symlink

Is it possible, executing a file symlinked in /usr/local/bin folder, to get the absolute path of original script? Well, .. I know where original file is, and I know it because I am linkging it. But, ... I want this script working, even if I move original source code (and symlink).

#!/bin/bash echo "my path is ..." 
like image 893
sensorario Avatar asked Apr 22 '15 06:04

sensorario


People also ask

How do I get the path of a Bash script?

The accepted answer to Getting the source directory of a Bash script from within addresses getting the path of the script via dirname $0 , which is fine, but that may return a relative path (like . ), which is a problem if you want to change directories in the script and have the path still point to the script's ...

How do I follow a symbolic link in Linux?

In order to follow symbolic links, you must specify ls -L or provide a trailing slash. For example, ls -L /etc and ls /etc/ both display the files in the directory that the /etc symbolic link points to. Other shell commands that have differences due to symbolic links are du, find, pax, rm and tar.


1 Answers

readlink is not a standard command, but it's common on Linux and BSD, including OS X, and it's the most straightforward answer to your question. BSD and GNU readlink implementations are different, so read the documentation for the one you have.

If readlink is not available, or you need to write a cross-platform script that isn't bound to a specific implementation:

If the symlink is also a directory, then

cd -P "$symlinkdir" 

will get you into the dereferenced directory, so

echo "I am in $(cd -P "$symlinkdir" && pwd)" 

will echo the fully dereferenced directory. That said, cd -P dereferences the entire path, so if you have more than one symlink in the same path you can have unexpected results.

If the symlink is to a file, not a directory, you may not need to dereference the link. Most commands follow symlinks harmlessly. If you simply want to check if a file is a link, use test -L.

like image 169
kojiro Avatar answered Sep 20 '22 10:09

kojiro