0

How to copy all the content of the folder /foo/bar, which contains the file /foo/bar/a to an empty subfolder /foo/bar/subfolder without ending up with the file /foo/bar/subfolder/subfolder/a. Doing cp -r * subfolder/ in /foo/bar does not work.

The system is Ubuntu 18.04 LTS.

1
cd /foo
cp -Rp bar subfolder
mv subfolder bar

This avoids recursively creating a multitude of subfolder/subfolder directories on all Unix systems by creating subfolder alongside bar under /foo. It creates the new folder by copying bar recursively. The new directory is then moved into /foo/bar.

The sequence of commands could also have been

cd /foo
rsync -a bar/ subfolder
mv subfolder bar
  • +1 for teaching me something new – Weijun Zhou Apr 23 at 13:28
0

One solution is to use

cp -r . subfolder/

instead, however, this still prints the annoying "cannot copy a folder to itself" to stderr.

Using rsync instead solves the issue,

rsync -r . subfolder/
  • 1
    Note that the both commands would create subfolder/subfolder and that if you're not using GNU cp, you may also get infinite number of subfolders under subfolder (infinite = until the pathname becomes too long). – Kusalananda Apr 23 at 6:54
  • Thank you for the note on GNU cp, I didn't know about it. – Weijun Zhou Apr 23 at 13:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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