How can I derefence symbolic links in bash? [duplicate]
Asked Answered
A

2

48

How can I take any given path in bash and convert it to it's canonical form, dereferencing any symbolic links that may be contained within the path?

For example:

~$ mkdir /tmp/symtest
~$ cd /tmp/symtest/
/tmp/symtest$ mkdir -p foo/bar cat/dog
/tmp/symtest$ cd foo/bar/
/tmp/symtest/foo/bar$ ln -s ../../cat cat
/tmp/symtest/foo/bat$ cd ../../
/tmp/symtest$ tree
.
|-- cat
|   `-- dog
`-- foo
    `-- bar
       `-- cat -> ../../cat

6 directories, 0 files

How can I get the full canonical path of /tmp/symtest/foo/bar/cat (i.e: /tmp/symtest/cat)?

Andrewandrewes answered 29/7, 2009 at 1:46 Comment(2)
Thanks for that. My search-fu didn't find that question.Andrewandrewes
No worries. I only knew to look for it because I asked it. :)Etra
A
71

Thanks to Andy Skelton, it appears the answer is readlink -f:

$:/tmp/symtest$ readlink -f /tmp/symtest/foo/bar/cat
/tmp/symtest/cat
Andrewandrewes answered 29/7, 2009 at 1:48 Comment(1)
In macOS bash, the -f option is not present for readlink, it is used for the format of the related stat command, that shares a man page with readlink. The only valid readlink option for macOS bash appears to be: -n Do not force a newline to appear at the end of each piece of output.Lumper
M
-7

Here's a function that will resolve symbolic links
It's original purpose is to resolve the full path to the calling script pointed to by a /usr/bin symlink

# resolve symbolic links
function resolve_link() {
  local LINK_FILE=${1:-${BASH_SOURCE[0]}}
  local FILE_TYPE=`file $LINK_FILE | awk '{print $2}'`
  local LINK_TO=$LINK_FILE
  while [ $FILE_TYPE = "symbolic" ]; do
    LINK_TO=`readlink $LINK_FILE`
    FILE_TYPE=`file $LINK_TO | awk '{print $2}'`
  done
  echo $LINK_TO
}

BASH_SOURCE_RESOLVED=$(resolve_link)
echo $BASH_SOURCE_RESOLVED

It doesn't use recursion but then again I've never used recursion in bash

Meaghanmeagher answered 24/3, 2012 at 11:16 Comment(2)
Um, what? This is needlessly complicated, replicating the standard readlink -f functionality without need. Not to mention that the correct answer was posted 3 years ago...Unsupportable
P.S. See this SO answer: #1056171 for a saner solution for systems that don't have readlink -f, such as Mac OS X.Unsupportable

© 2022 - 2024 — McMap. All rights reserved.