3

I want to recursively copy a dir and have the targets of the links copied, but I do not want the cp to stop if a target of a link does not exist.

For example, I run this command:

cp -fprL /path/to/src_dir /path/to_dest_dir

But the first time it hits symlink where the target doesn't exist it exits:

cp: cannot stat `/path/to/non-existent/file': No such file or directory

Is there some way to get cp to silently skip these and continue on?

1

1 Answer 1

2

With the standard GNU toolchain, no, there's no way.

You could instead copy your files, keeping symlinks as symlinks, then use find -follow -type l -delete to delete the broken symlinks, and then copy again, this time following symlinks.

Of course, you could also just write a python etc. program to do the copy for you, or find all files in the original trees that are not broken symlinks and use these with cp, replacing parts of the path with the target path using sed:

find -type d|sed 's/^\(.*\)/"\1" "\/target\/\1"/g'|xargs -p mkdir
find -follow -not -type l -not -type d|sed 's/^\(.*\)/"\1" "\/target\/\1"/g'|xargs -n2 cp

sed will duplicate your found file path, prefixing it with the target directory.

7
  • This is prone to potentially dangerous misbehavior if any filenames contain literal newlines. (Then again, following symlinks in general is unsafe if any directory inside the area covered is world-writable). Commented Jan 10, 2015 at 0:08
  • Very true, Charles Duffy. The same goes for " , by the way. You can work around that using print0 for find, and -0 for xargs, but things usually get ugly with 0 delimited strings in sed. Commented Jan 10, 2015 at 0:12
  • Indeed. One could work around that by doing the replacement in native bash rather than sed, given the inclination. Commented Jan 10, 2015 at 0:14
  • Oh, how would one go about doing that? My bash-foo is weak... I'd personally rather just abuse python for a while, but I'm eager to learn. Commented Jan 10, 2015 at 0:15
  • so, to iterate over an incoming NUL-delimited stream: while IFS= read -r -d '' filename; do. To replace would be out=${in//$src/$dest}, but if you're trying to replace only at the beginning of a string there are better approaches, all covered in the parameter expansion documentation. To generate another NUL-delimited stream on the output end, printf '%s\0' "$out" within the while read loop, if you aren't inclined to just invoke cp from within said loop directly. Commented Jan 10, 2015 at 0:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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