8

How can I get the full path to a symlink without resolving it to the path of the original file?

For example, if I have a directory set up like this:

~$ tree analysis_results/
analysis_results/
`-- Sample1
    `-- bar.txt -> /Users/me/foo.txt

If I try to get the full path to bar.txt, I end up with the path to foo.txt instead:

~$ readlink -f analysis_results/Sample1/bar.txt
/Users/me/foo.txt

But what I really want is this:

/Users/me/analysis_results/Sample1/bar.txt

Is there a simple way to accomplish this? It looks like I do not have realpath available, not sure if that program does this, or if there is some other command that works like this.

Things get more complicated when my pwd is something like:

/Users/me/analysis/peaks/workflow/code

But I want to read the full path to a symlink like:

/Users/me/analysis/alignment/results/Sample1/bar.txt
user5359531
  • 3,217
  • 6
  • 30
  • 55

4 Answers4

5

With GNU realpath:

$ touch foo
$ ln -s foo bar
$ realpath --no-symlinks bar
/path/to/bar
bishop
  • 37,830
  • 11
  • 104
  • 139
  • this sounds perfect, unfortunately `realpath` isn't available on my OS, CentOS 6 (just updated the OP with this information). I'll have to look into getting it installed. – user5359531 Jan 27 '17 at 19:53
  • @user5359531 You can also [do something similar in Perl](http://stackoverflow.com/a/16372849/2908724) if Centos YUM doesn't work out. – bishop Jan 27 '17 at 20:18
2
echo "$(readlink -f analysis_results/Sample1)/bar.txt"

Resolve only the directory and then append the filename to the result.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
1

You want the full path with any intermediate symlinks resolved?

From the "yet another way to do it" category: Your pwd command probably has a "-P" option to print the physical path to a directory. So, you could wrap a cd and pwd in () to get something like

user@host[/tmp]
$ mkdir test
user@host[/tmp]
$ ln -s test linkdir
user@host[/tmp]
$ (cd /tmp/linkdir; pwd -P)
/tmp/test

So, all you're doing is cd $(dirname $yourfile) and then running pwd -P to get the physical path to the parent directory. It's wrapped in parens in the example so it creates a subshell and doesn't impact your current working directory.

dannysauer
  • 3,793
  • 1
  • 23
  • 30
0

practical example

To get the parent path of a bash script folder,

  • ...gladly ignoring that its folder is actually a symlink from somewhere else...

This combination of parameter substitution, inner shell and realpath does the deed:

For example, to 'include' ../something. The inner cd goes out of scope with the backtick that follows.

echo $(realpath --no-symlinks `cd ..; echo $(pwd)`)
source $parentDir/helper-library.sh
Frank N
  • 9,625
  • 4
  • 80
  • 110