2

Is it possible to convert in a shell script a user input path (absolute or relative) to the absolute path but without losing the symlinks inside, e.g. /a/b/c is the current user dir and c is a symlink to /a/b/s:

input .      => result /a/b/c
input ./d    => result /a/b/c/d
input ../c   => result /a/b/c
input /a/b/c => result /a/b/c
(readlink converts it to /a/b/s, but I need /a/b/c)
hellcode
  • 742
  • 1
    “Without losing the symlinks” and eliminating .. is contradictory: if f is a symlink to /elsewhere, for f/../stuff, do you want /a/b/stuff (eliminating .. without looking up symlinks, but you end up with a path that doesn't lead to the same file) or /elsewhere/stuff (which is correct but doesn't go through a symlink) or /a/b/f/../stuff (which is correct but retains ..)? The considerations in http://unix.stackexchange.com/questions/9123/is-there-a-one-liner-that-allows-me-to-create-a-directory-and-move-into-it-at-th/9124#9124 may be of interest. – Gilles 'SO- stop being evil' Mar 05 '15 at 22:54
  • Hi @Gilles: thanks and you are right with your example, but in my case this doesn't play a major role. – hellcode Mar 06 '15 at 15:20

1 Answers1

2

If I understand your question correctly you need to use realpath with -s:

-s, --strip Only strip . and .., components, but do not resolve symbolic links.

$ realpath -s a/b/c
/tmp/a/b/c
$ readlink a/b/c
s
  • Thank you, but realpath is not installed by default and the script should run on servers where I can't install it. – hellcode Mar 05 '15 at 16:21
  • What system is that? You don't need to be root to install a program, you can put in your home dir and add it to your $PATH. – Arkadiusz Drabczyk Mar 05 '15 at 16:33
  • I just installed realpath to test it. realpath -s /a/b/c and realpath -s ../c/d work as expected, but not with one dot at the beginning: realpath -s ./d outputs /a/b/s/d. But this can be fixed in the script. I will test to copy the binary file to the destination server. Hope it will work :-) Thanks again. – hellcode Mar 05 '15 at 17:04