zl程序教程

您现在的位置是:首页 >  其他

当前栏目

日更第2天:Linux常用命令之cp用法

2023-04-18 16:09:01 时间
21天掌握Linux常用命令挑战

1. 命令简介

cp重点在于复制,主要将一个或多个源文件或者文件夹复制到指定的目的文件或文件夹(可以理解为在window系统上操作,根据自己所需复制文件或文件夹粘贴到指定位置)

2. 英文含义记忆法

cp = copy

3. 语法格式

  • cp 选项... -T 源文件 目标文件
  • cp 选项... 源文件... 目录
  • cp 选项... -t 目录 源文件...

4. 选项说明

  • -r: 将一个文件夹及文件夹下所有内容拷贝到另外一个文件夹
  • -i:与 -f 选项相反,在覆盖目标文件之前给出提示,要求用户确认是否覆盖,回答 y 时目标文件将被覆盖
  • -f:覆盖已经存在的目标文件而不给出提示
  • -a:原样复制,保留全部(包括时间、访问权限、文件的所有者等)
  • -p:保留源文件或目录的属性
  • -l:不复制文件,只是生成链接文件
  • -v:详细显示命令执行的操作

5.注意事项

  • 源文件:默认情况下,cp命令不能复制文件夹,如果要复制文件夹,则必须使用-R选项;
  • 目标文件:当源文件为多个文件时,要求目标文件为指定的目录。

6. 示例说明

6.1 将一个文件夹及文件夹下所有内容拷贝到另外一个文件夹

cp -r /folder1 /folder2

[root@iZbp1d8rn0652ia3bzzmioZ local]# cd test1/
[root@iZbp1d8rn0652ia3bzzmioZ test1]# ls -l
总用量 0
-rw-r--r-- 1 root root 0 11月 23 23:00 111111.txt
-rw-r--r-- 1 root root 0 11月 23 23:00 1111.txt
-rw-r--r-- 1 root root 0 11月 23 22:59 111.txt
[root@iZ test1]# cd ../test2/
[root@iZ test2]# ls
[root@iZ test2]# cp -r /usr/local/test1/ /usr/local/test2/
[root@iZ test2]# ls
test1
[root@iZ test2]# cd test1/
[root@iZ test1]# ls
111111.txt  1111.txt  111.txt
[root@iZ test1]#

6.2 将一个文件夹下所有内容拷贝到另外一个文件夹下

cp -r /folder1/* /folder2

drwxr-xr-x   2 root root   55 11月 23 23:00 test1
drwxr-xr-x   2 root root    6 11月 23 23:07 test2
[root@iZ local]# cd test1/
[root@iZ test1]# ls
111111.txt  1111.txt  111.txt
[root@iZ test1]# cd ../test2/
[root@iZ test2]# ls
[root@iZ test2]# cp /usr/local/test1/* /usr/local/test2
[root@iZ test2]# ls
111111.txt  1111.txt  111.txt
[root@iZ test2]#

6.3 目标文件下已经存在复制文件时,在覆盖时会先询问是否执行操作

cp -i /folder1/xxx.txt /folder2

[root@iZ test2]# ls
111111.txt  1111.txt  111.txt
[root@iZ test2]# cd ../test1/
[root@iZ test1]# ls
111111.txt  1111.txt  111.txt
[root@iZ test1]# cp -i 111.txt /usr/local/test2
cp:是否覆盖'/usr/local/test2/111.txt'? y
[root@iZ test1]#

6.4 原样复制,保留全部

cp -a 1111.txt /usr/local/test2/

[root@iZ test1]# ls -l
总用量 0
-rw-r--r-- 1 root root 0 11月 23 23:00 111111.txt
-rw-r--r-- 1 root root 0 11月 23 23:00 1111.txt
-rw-r--r-- 1 root root 0 11月 23 22:59 111.txt
[root@iZ test1]# cp 111.txt /usr/local/test2/
[root@iZ test1]# cd /usr/local/test2/
[root@iZ test2]# ls -l
总用量 0
-rw-r--r-- 1 root root 0 11月 23 23:28 111.txt
[root@iZ test1]# ls -l
总用量 0
-rw-r--r-- 1 root root 0 11月 23 23:00 111111.txt
-rw-r--r-- 1 root root 0 11月 23 23:00 1111.txt
-rw-r--r-- 1 root root 0 11月 23 22:59 111.txt
[root@iZ test1]# cp -a 1111.txt /usr/local/test2/
[root@iZ test1]# cd /usr/local/test2/
[root@iZ test2]# ls -l
总用量 0
-rw-r--r-- 1 root root 0 11月 23 23:00 1111.txt
-rw-r--r-- 1 root root 0 11月 23 23:28 111.txt

好了,今天的学习就到这里!欢迎大家评论区参与交流与讨论,更好的学习与进步!

系列推荐