0

How can I copy a folder that contains symlinks and retain the symlinks in the destination folder? I'm doing something like this with PHP/Bash:

system("cp -r production-clone-target production-sites/{$instanceName}");

but the symlinks do not appear in the destination folder.

4
  • 1
    On BSD: cp -PR source destination. On Linux: cp -dr source destination. However, with PHP there are probably much better approaches than running system() (why do you have system() enabled, in the first place?). Oct 21, 2016 at 7:39
  • You mean from a security standpoint?
    – shmuli
    Oct 21, 2016 at 7:43
  • I'd bet many things that the answer is yes. See stackoverflow.com/questions/3115559/exploitable-php-functions
    – schaiba
    Oct 21, 2016 at 7:48
  • 1
    This seems to be a far more reasonable solution. Oct 21, 2016 at 7:49

3 Answers 3

3

Try adding the --preserve=links switch to your cp command.

From man cp:

    --preserve[=ATTR_LIST]
          preserve the specified attributes (default: mode,ownership,timestamps), 
if possible additional attributes: context, links,xattr, all

Edit: If under OS X; use cp -a.

4
  • 1
    Assuming Linux FTW. Oct 21, 2016 at 7:39
  • @SatoKatsura True, fixed!
    – anon
    Oct 21, 2016 at 7:41
  • 1
    On OpenBSD: "cp: unknown option -- a" Oct 21, 2016 at 7:42
  • @SatoKatsura Huh! Didn't know that, thanks for the info, just tested under OS X, where the -a switch works. Thought it was the same for all BSD's.
    – anon
    Oct 21, 2016 at 7:44
1

You can use also rsync:

-l, --links                 copy symlinks as symlinks

I like -a, which also includes this one, to copy also sub-directories etc.

-a, --archive               archive mode; equals -rlptgoD (no -H,-A,-X)

So, in your code example you could do this:

system("rsync -a production-clone-target production-sites/{$instanceName}");
0

Setting aside the valid concerns about using system() in your PHP program:

cp may not have standardized options for doing this that are common to Linux and the BSDs, but pax has.

( cd source && pax -p p -r -w * destination/ )

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .