在 Linux 中使用 cp 命令
cp
![](/data/attachment/album/202308/12/135152eqsy2yiczqiicqvt.jpg)



> 
> 熟悉在 Linux 命令行中复制文件和目录的 cp 命令。
> 
> 
> 


`cp` 命令是 Linux 中一个重要的命令，你可能经常会用到它。


正如名称所示，`cp` 代表 <ruby> 复制 <rt>  copy </rt></ruby>，它被用于 [在 Linux 命令行中复制文件和目录](https://itsfoss.com/copy-files-directory-linux/)。


这是一个相对简单的命令，只有几个选项，但你仍有必要深入了解它。


在展示 `cp` 命令的实际示例之前，我更建议你先熟悉绝对路径和相对路径的概念，将文件从一个位置复制到另一个位置时，你需要用到它们。



> 
> [Linux 中的绝对路径和相对路径的不同之处](https://linuxhandbook.com/absolute-vs-relative-path/)
> 
> 
> 


### 复制单个文件


`cp` 命令最简单和最常见的用途是复制文件，只需指定源文件和要“粘贴”文件的目标目录即可。



```
cp 源文件 目标目录

```

![将单个文件从源目录复制到目标目录。](/data/attachment/album/202308/12/135235cm6fw9mpoomo5hot.png)


### 在复制文件的同时重命名它


你将文件复制到另一个位置时可以同时进行 [重命名](https://learnubuntu.com:443/rename-files/)。这有点类似于文本编辑器中的“另存为”选项。


为此，你必须在路径中给出新的文件名。



```
cp 源文件 目标目录/新文件名

```

![在复制文件的同时重命名](/data/attachment/album/202308/12/135237b433kr8xpqpp2q2p.png)


### 复制多个文件


你还可以将多个文件复制到另一个位置。



```
cp 文件1 文件2 文件3 目标目录

```

![复制多个文件时，将目标目录放在最后](/data/attachment/album/202308/12/135238htv73fsu2yzvsbvb.png)


在这种情况下，你无法重命名文件。


你还可以使用通配符扩展，将特定后缀的文件复制到另一个位置：



```
cp *.txt 目标目录

```

![使用通配符扩展复制多个文件，比如所有 .txt 后缀的文件](/data/attachment/album/202308/12/135238zj00io3wywwlwfyj.png)


### 复制文件时避免覆盖现有文件


如果你将 `file1.txt` 复制到一个已经存在名为 `file1.txt` 文件的目录中，它会将原有的文件覆盖掉。


如果你不希望这样，`cp` 命令还提供了几个选项来处理文件覆盖的情况。


首先是使用选项 `-i` 的交互模式。在交互模式下，它会询问是否确认或放弃覆盖目标文件。



```
cp -i 源文件 目标目录
cp：覆盖 '目标目录/源文件' ？

```

按 `Y` 覆盖文件，按 `N` 跳过复制该文件。


![覆盖，但以交互方式询问（内容将被覆盖）](/data/attachment/album/202308/12/135238prfrgdzggjg9fsgj.png)


![覆盖，但以交互方式询问（内容不会被覆盖）](/data/attachment/album/202308/12/135239o4xr35wfaqrz83s6.png)


选项 `-n` 代表完全取消覆盖。使用此选项时目标文件不会被覆盖。



```
cp -n 源文件 目标目录

```

![取消覆盖（目录内文件的内容未更改）](/data/attachment/album/202308/12/135239jmzpo7e915h01ts5.png)


还有一个选项 `-b`，在目标目录的文件将被覆盖时自动为其创建备份。我猜这里 `b` 代表 <ruby> 备份 <rt>  backup </rt></ruby>。



```
cp -b 源文件 目标目录

```

![覆盖文件，但在备份文件后附加了“~”。](/data/attachment/album/202308/12/135240h9cyr9hzbwxay067.png)


最后，还有一个“<ruby> 更新 <rt>  update </rt></ruby>”选项 `-u`，如果目标文件比源文件旧，或者目标文件不存在，就会被覆盖掉。



```
cp -u 源文件 目标目录

```

![新文件会覆盖旧文件](/data/attachment/album/202308/12/135240aqvqvqqxxtrv4vql.png)


### 复制目录（文件夹）


cp 命令也用来[在 Linux 命令行中复制目录](https://linuxhandbook.com:443/copy-directory-linux/)。


在复制目录时，你需要使用递归选项 `-r`。



```
cp -r 源目录 目标目录

```

![在 Linux 中使用 cp 命令复制整个目录](/data/attachment/album/202308/12/135240vx11dkdywyrc9wfd.png)


你还可以将多个目录复制到另一个位置：



```
cp -r 目录1 目录2 目录3 目标目录

```

![使用 cp 命令复制多个目录](/data/attachment/album/202308/12/135241ormufj8982n8gzmy.png)


### 在复制时保留属性


当你将文件复制到另一个位置时，它的 [时间戳](https://linuxhandbook.com:443/file-timestamps/)、[文件权限](https://linuxhandbook.com:443/linux-file-permissions/) 甚至所有权都会发生变化。


这是正常的行为。但在某些情况下，你可能希望在复制文件时保留其原始属性。


要保留属性，请使用选项 `-p`：



```
cp -p 源文件 目标目录

```

![](/data/attachment/album/202308/12/135241b11zrkk7kdm01nok.png)



> 
> ? 还有一个 `-a` 选项用于存档模式。它将连 ACL 也保留下来。
> 
> 
> 


### ?️ 练习时间


想要练习一下 `cp` 命令吗？以下是一些简单的练习题供你尝试。


* 打开终端并创建一个名为 `practice_cp` 的目录。
* 现在，将 `/etc/services` 文件复制到这个新创建的目录中。
* 在 `practice` 目录中对复制的 `services` 文件进行一些小的更改。
* 现在，使用更新模式再次复制 `/etc/services` 文件。有什么变化吗？观察一下。
* 查看 `/var/log` 目录，并将以 `mail` 开头的日志文件复制到你的联系目录下。
* 现在，返回到你的家目录，并创建一个名为 `new_dir` 的新目录（好吧，我想不出更好的名字）。
* 将 `practice_cp` 目录复制到 `new_dir` 目录中。


对你来说这些练习足够用了。希望你能喜欢在这里学习 Linux 命令。


*（题图：MJ/07b35a39-826e-4904-9f85-25257831ce9d）*




---


via: <https://itsfoss.com/cp-command/>


作者：[Abhishek Prakash](https://itsfoss.com/author/abhishek/) 选题：[lkxed](https://github.com/lkxed/) 译者：[onionstalgia](https://github.com/onionstalgia) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
![Warp Terminal](/assets/images/warp-terminal.webp)


![Warp Terminal](/assets/images/warp-terminal.webp)

The cp command is one of the essential Linux commands you probably will be using on a regular basis.

As the name indicates, cp stands for copy and it is used for [copying files and directories in Linux command line](https://itsfoss.com/copy-files-directory-linux/).

It's one of the simpler commands with only a few options but that doesn't mean you cannot know more about it.

Before you see some practical examples of the cp command, I advise getting familiar with the concept of absolute and relative paths because you'll need to use them while copying files from one place to another.

[Absolute vs Relative Path in Linux: What’s the Difference?In this essential Linux learning chapter, know about the relative and absolute paths in Linux. What’s the difference between them and which one should you use.](https://linuxhandbook.com/absolute-vs-relative-path/?ref=itsfoss.com)![](https://linuxhandbook.com/content/images/2021/04/absolute-relative-path-linux.png)


![](https://linuxhandbook.com/content/images/2021/04/absolute-relative-path-linux.png)

## Copy a file

The simplest and most common use of the cp command is for copying files. For that, you just have to specify the source file and the destination where you want to 'paste' the file.

`cp source_file destination_directory`


![Copy a file from the source directory to a destination](https://itsfoss.com/content/images/2023/07/cp_2.png)

## Rename the file while copying it

You can also [rename the file](https://learnubuntu.com/rename-files/) while copying it to another location. This is like those 'save as' options you see in text editors.

For this, you must mention the new file name along with the path.

`cp source_file destination_directory/new_filename`


![Rename the file while copying](https://itsfoss.com/content/images/2023/07/cp_rename.png)

## Copy multiple files

You can also copy multiple files to another location.

`cp file1 file2 file3 destination_directory`


![Copy multiple files, with destination directory at the end](https://itsfoss.com/content/images/2023/07/cp_multiple_files-1.png)

You cannot rename files in this case.

Of course, you can use wildcard expansion and copy files of a certain type to another location:

`cp *.txt destination_directory`


![Copy multiple files with Wildcard expansion, which is all files with .txt extension](https://itsfoss.com/content/images/2023/07/cp_multiple_files-wildcard_expansion-.png)

## Avoid overwriting while copying files

If you are copying file1.txt to a directory where there already exists a file named file1.txt, it will be overwritten with the file you are copying.

You may not always want that. This is why the cp command provides several options to deal with overwriting.

The firstmost is the interactive mode with the option `-i`

. In the interactive mode, it will ask you to confirm or deny the overwriting of the destination file.

```
cp -i source_file destination_directory
cp: overwrite 'destination_directory/source_file'?
```


Press Y to overwrite and N to skip copying the file.

![Overwrite, but ask interactively (content overwritten)](https://itsfoss.com/content/images/2023/07/cp_overwrite--i-.png)

![Overwrite, but ask interactively (content is NOT overwritten)](https://itsfoss.com/content/images/2023/07/cp_overwrite--i-_unchanged.png)

The option `-n`

negates overwriting completely. Destination files won't be overwritten with this option.

```
cp -n source_file destination_directory
```


![Negated Overwriting (content of the file inside the directory has not changed)](https://itsfoss.com/content/images/2023/07/cp_overwrite_-n.png)

There is also an option `-b`

for automatically creating a backup if the destination file is going to be overwritten. B stands for backup, I presume.

```
cp -b source_file destination_directory
```


![Overwriting a file, but with a backup file appended by '~'](https://itsfoss.com/content/images/2023/07/cp_overwrite_-b-1.png)

And lastly, there is the 'update' option `-u`

which will overwrite the destination file if it is older than the source file or if it destination file does not exist.

`cp -u source_file destination_directory`


![The newer file is overwritten into the older file](https://itsfoss.com/content/images/2023/07/cp_overwrite--u--1.png)

## Copy directories (folders)

The cp command is also used for [copy directories in the Linux command line](https://linuxhandbook.com/copy-directory-linux/).

You need to use the recursive option `-r`

for copying directories.

`cp -r source_dir destination_dir`


![Copy a directory using cp command in Linux](https://itsfoss.com/content/images/2023/07/cp_directories_1-1.png)

You can also copy multiple directories to another location:

`cp -r dir1 dir2 dir3 target_directory`


![Copying multiple directories using cp command](https://itsfoss.com/content/images/2023/07/cp_directories_2-1.png)

## Preserve attributes while copying

When you copy a file to another location, its [timestamp](https://linuxhandbook.com/file-timestamps/), [file permission](https://linuxhandbook.com/linux-file-permissions/) and even ownership gets changed.

That's the normal behavior. But in some cases, you may want to preserve the original attribute even when you are copying the file.

To preserve the attributes, use the option `-p`

:

`cp -p source_file destination_directory`


![](https://itsfoss.com/content/images/2023/07/cp_preserve_attributes.png)

There is also `-a`

option for archive mode. It will preserve even the ACLs.

## 🏋️ Exercise time

Want to practice the cp command a little? Here are some simple exercises for you.

- Open a terminal and create a directory named
`practice_cp`

- Now, copy the /etc/services file in this newly created directory.
- Make some minor changes to the copied services file in practice directory.
- Now, copy /etc/services file again but in update mode. Does it change anything? Observe.
- Look into /var/log directory and copy the log files that start with mail into your practice directory
- Now, go back to your home directory and create a new directory named new_dir (well, I couldn't think of any better)
- Copy the practice_cp directory to new_dir

That should be good enough exercise for you. Enjoy learning Linux commands with It's FOSS.