UNIX command to dereference a symbolic link?

6

1

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.

dehmann

Posted 2011-07-14T19:05:36.470

Reputation: 1 853

Answers

10

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.

Roman Cheplyaka

Posted 2011-07-14T19:05:36.470

Reputation: 351

4

Combining both answers leads to the following:

#!/bin/bash

if [ -h "$1" ] ; then
  target=`readlink $1`
  rm "$1"
  cp "$target" "$1"
fi

phlogratos

Posted 2011-07-14T19:05:36.470

Reputation: 141

3

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?).

Marcus Borkenhagen

Posted 2011-07-14T19:05:36.470

Reputation: 131

0

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

rm b
cp a b

ennuikiller

Posted 2011-07-14T19:05:36.470

Reputation: 980

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 – 2011-07-14T19:10:50.017