cp -r 和 cp -R 的区别(复制命令)

its*_*_me 82 linux cp

cp -r用于递归复制文件,以及cp -R递归复制目录。但我已经检查过,两者似乎都复制了文件和目录,同样的事情。那么,实际上有什么区别呢?

and*_*coz 92

虽然-Rposix 定义明确,但-r不可移植!

在 Linux 上,在 GNU 和 BusyBox 实现中cp,-r和-R是等价的。

另一方面,正如您在POSIX手册页中所读到的cp,-r行为是实现定义的。

    * If  neither  the  -R  nor  -r  options were specified, cp shall take
      actions based on the type and contents of the file referenced by the
      symbolic link, and not by the symbolic link itself.

    * If the -R option was specified:

       * If  none  of  the  options  -H,  -L, nor -P were specified, it is
         unspecified which of -H, -L, or -P will be used as a default.

       * If the -H option was specified, cp shall take  actions based on
         the type and contents of the file referenced by any symbolic link
         specified as a source_file operand.

       * If the -L option was specified, cp shall take  actions based  on
         the type and contents of the file referenced by any symbolic link
         specified as a source_file operand or any symbolic links encoun-
         tered during traversal of a file hierarchy.

       * If  the  -P option was specified, cp shall copy any symbolic link
         specified as a source_file operand and any symbolic links encoun-
         tered  during traversal of a file hierarchy, and shall not follow
         any symbolic links.

    * If the -r option was  specified,  the  behavior  is implementation-
      defined.
Run Code Online (Sandbox Code Playgroud)

  • 区别之一是,例如在 OSX 中,`-r` 将复制符号链接指向的真实文件,而`-R` 将复制符号链接,这在大多数情况下是它的目的。 (17认同)

Ran*_*832 22

小写-r是一个较旧的选项,在 4.1BSD 中引入,它会简单地将所有非目录复制为文件。也就是说,如果它遇到一个设备或 FIFO,它会打开它,读取内容,并在目的地创建一个包含内容的文件。

大写-R是一个标准化选项(在 4.4BSD 中引入 BSD,尽管早期版本将它作为 的同义词-r),当遇到设备、FIFO 或其他特殊文件时,它会在目的地生成一个等效的特殊文件。

许多实现仍然保持这种区别,但有些(包括 Linux 典型的 GNU 版本)只提供-R语义,-r作为同义词。


Ign*_*ams 18

区别在于一个使用小写的“R”,另一个使用大写的“R”。除此之外,没有区别。如果你使用--recursivelong 选项,同样的事情。

  • -R 和 -r 在我使用的某些系统(OS X、FreeBSD、BusyBox coreutils;目前不确定是哪些)上给出了不同的行为。我很久以前就决定始终只使用 `-R` 是明智的,事实上,刚刚提到的系统上的一些手册页也建议这样做。 (7认同)
  • @DaveJennings:仅仅因为它们在一个平台上是等效的并不意味着它们在所有平台上都是等效的。在 `cp` 的一些实现中,实际上是有区别的。参见 [Random832 的回答](http://unix.stackexchange.com/questions/18712/difference-between-cp-r-and-cp-r-copy-command/18722#18722)。@Ignacio 你应该在这个答案中包含一个限定词,上面写着“如果你的 `cp` 是现代 GNU 实现”或类似的东西。 (6认同)
  • 从手册页: -R, -r, --recursive - 递归复制目录 (4认同)