Is there a UNIX command to dereference a symbolic link? I would like to replace the link by a copy of the file it points to.

Example:

$ ls
a
b -> a

$ deref b
$ ls 
a
b

Now, a and b have the same content but are independent of each other. My question is if there is such a deref command. Important: I don't have to know where b points to; the command should figure that out.

link|improve this question

63% accept rate
feedback

migrated from stackoverflow.com Jul 15 '11 at 0:59

This question came from our site for professional and enthusiast programmers.

4 Answers

up vote 4 down vote accepted

You can use readlink to find out the filename, but you don't have to!

cp b c
mv c b

It's that simple. If you are writing a script to do that, you should use the output of mktemp instead of c to make sure you don't override already existing file c.

link|improve this answer
feedback

It is possible by copying whatever the symlink points to...

see readlink(1) and cp(1). Update: and while you're at it: readlink(2).

BUT a symlink is really just that, a symbolic (read: by means of the name of the target) link to another file - it does not share the content of the other file. (hardlink, anyone?).

link|improve this answer
feedback

Combining both answers leads to the following:

#!/bin/bash

if [ -h "$1" ] ; then
  target=`readlink $1`
  rm "$1"
  cp "$target" "$1"
fi
link|improve this answer
feedback

There's no such command, but you can do the following:

rm b
cp a b
link|improve this answer
That's not ideal because I have to know where b points to. I'd like to avoid having to find that out myself. – dehmann Jul 14 '11 at 19:10
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.