Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a symbolic link to a file in one directory. I would like to have that same link in another directory. How do I copy a symbolic link?

I tried to cp the symbolic link but this copies the file it points to instead of the symbolic link itself.

share|improve this question
1  
Does cp on CentOS support -P or --no-dereference switch? –  manatwork Nov 19 '12 at 9:10
    
@manatwork: Thanks it does just found that. If you want to post it as an answer I'll accept it. –  User Nov 19 '12 at 9:14
add comment

2 Answers

up vote 6 down vote accepted

Use cp -P (capital P) to never traverse any symbolic link and copy the symbolic link instead.

This can be combined with other options such as -R to copy a directory hierarchy — cp -RL traverses all symbolic links to directories, cp -RP copies all symbolic links as such. cp -R might do one or the other depending on the unix variants; GNU cp (as found on CentOS) defaults to -P.

Even with -P, you can copy the target of a symbolic link to a directory on the command line by adding a / at the end: cp -RP foo/ bar copies the directory tree that foo points to.

GNU cp has a convenient -a option that combines -R, -P, -p and a little more. It makes an exact copy of the source (as far as possible), preserving the directory hierarchy, symbolic links, permissions, modification times and other metadata.

share|improve this answer
    
Beware that once copied/moved, a symlink might become broken (if the source is a symlink to a relative path). –  Stephane Chazelas Dec 10 '13 at 7:03
    
is there a way to prevent breaking the symlinks if you are moving to a higher or lower directory? –  Andrew Brown Mar 20 at 7:05
add comment

Check this answer http://superuser.com/a/315757/53590 for a specifically CentOS take on the problem. The whole question might help you but the bit at the bottom is specifically CentOS.

share|improve this answer
1  
Note that others may choose a different order than yours for listing the answers. Beside that, the order may change in time. Please post a direct link to the referred answer. (Click the “share” link below that answer and copy the direct link which appears.) –  manatwork Nov 19 '12 at 9:30
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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