Linux cp command to copy folders: copy content of the folder vs copy folder

How to understand whether cp will copy the content of the folder or the folder itself.
For example, I have a file /some/path/text.txt.
If I do cp -r /some/path /another/path2, the new path of the file will be /another/path2/text.txt?
If I do cp -r /some/path/ /another/path2, the new path is /another/path2/text.txt?
If I do cp -r /some/path/ /another/path2/, what will happen?
If I do cp -r /some/path /another/path2/, what will happen?
I'm always confused about this and many times I correct my wrong copying. I tried to find information about this but didn't find any structured information

1 Answer

In most cases it doesn't matter. Instead, 'cp' decides based on whether the destination exists.

Assuming the source is always a directory, and you're using either cp -r or cp -a:

  1. If the source is a symlink to a directory, then the trailing slash after the source is important. Without it, you'd be only copying the symlink itself and not the directory it points to.

    If the source isn't a symlink, the trailing slash after the source doesn't matter to 'cp'.

  2. If the target points to an existing directory, then the whole source directory will be copied into the target. That is, cp -r abc def will cause def/abc/text.txt to be created. Trailing slashes on the source nor the destination do not matter.

    If the target doesn't exist, then the source directory will be copied as the target. That is, cp -r abc def will only create def/text.txt. Trailing slashes don't affect anything here, either.

The 2nd "rule" can be annoying, as it seems like you cannot copy an existing directory's contents directly into another directory without resorting to something like abc/* (which will miss hidden files), etc.

However, an easy way to achieve that is to specify . as the last path component – this will trick cp into "creating" a . in the destination:

cp -r /some/path/. /another/path

Trailing slash on the destination still doesn't matter.

(Note that these rules are not universal for all programs; in particular, rsync behaves differently and trailing slashes indeed tell it whether to copy the whole directory or only its contents.)


In short:

  • If you want to copy the directory whole, ensure the destination already exists (pre-create it using mkdir).
  • If you want to copy the directory's contents, make sure to end the source with /. (slash + dot) (like the website).

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like