6

I want to copy a directory into another directory.

For example, cp -r dir1 dir2 copies the contents of dir1 into dir2. I want to copy dir1 itself into dir2 so that if I ls dir2 it will output dir1 and not whatever was inside of dir1.

0

3 Answers 3

7

Just do as you did:

cp -r dir1 dir2

and you will have dir1 (with its content as well) inside dir2. Try if you don't believe ;-).

The command that would copy content of dir1 into dir2 is:

cp -r dir1/* dir2

3
  • I tried it out exactly so and it worked. Then I went back to my original location and tried it, didn't work. Turns out bash's auto-complete suggested cp -r System\ Volume\ Information test only copies the contents, but if I manually type it out as cp -r "System Volume Information" test then it copies the directory itself and not just the contents. Commented Aug 10, 2014 at 18:00
  • I'll mark this answer as accepted because it is correct. The actual cause of the problem though was the spaces as described above. Commented Aug 10, 2014 at 18:23
  • 2
    @EricMajerus Your explanation of the cause does not make sense. I have added a new answer, that may explain things, it may be that the order of your tests, and not cleaning up after the first test cased the second to behave differently. Commented Aug 10, 2014 at 21:35
5

Look at the manual for cp (also mv):

   cp [OPTION]... [-T] SOURCE DEST
   cp [OPTION]... SOURCE... DIRECTORY
   cp [OPTION]... -t DIRECTORY SOURCE...

If you do cp a b then if b does not exist you get cp -T a b, but if b exists and is a directory you get cp -t b a, else error.


Example

mkdir empty
cd empty
mkdir a
touch a/a-file
cp -r a b #this creates b a copy of a
cp -r a b #this time it makes a copy of a called a in b (b/a)

Example 2

mkdir empty
cd empty
mkdir a
touch a/a-file
cp -r -T a b #this creates b, a copy of a
cp -r -T a b #updates b (no effect in this case)

Example 3

mkdir empty
cd empty
mkdir a
touch a/a-file
mkdir b
cp -r -t b a #copy a into b
cp -r -t b a #updates a/b (no effect in this case)
1
  • thank you so much for the examples, resolved 15 min of painful debugging for me this morning!!
    – J-Dizzle
    Commented Feb 24, 2018 at 17:49
2

Also, make sure that the first argument (the directory you want to copy) doesn't end with a forward-slash character /. Some versions of cp (for example on MacOS) treat it as /* and copy just the contents of the directory in such case, not the whole directory. And the forward-slash is usually added when you auto-complete the directory name using the Tab key.

Copy the whole directory dir1 into the directory dir2:

cp -r dir1 dir2

Copy the contents of the directory dir1 into the directory dir2:

cp -r dir1/ dir2

It's equivalent to:

cp -r dir1/* dir2

You must log in to answer this question.

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