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

Solution 1:

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).