cp命令用来复制文件或者目录,是Linux系统中最常用的命令之一。一般情况下,shell会设置一个别名,在命令行下复制文件时,如果目标文件已经存在,就会询问是否覆盖,不管你是否使用-i参数。但是如果是在shell脚本中执行cp时,没有-i参数时不会询问是否覆盖。这说明命令行和shell脚本的执行方式有些不同。
用法:
将源文件复制至目标文件,或将多个源文件复制至目标目录。
实例一:复制单个文件到目标目录,文件在目标文件中不存在
命令:
1 | cp log.log test5 |
输出:
123456789101112 | [root@localhost test]# cp log.log test5[root@localhost test]# ll-rw-r--r-- 1 root root 0 10-28 14:48 log.logdrwxr-xr-x 6 root root 4096 10-27 01:58 scfdrwxrwxrwx 2 root root 4096 10-28 14:47 test3drwxr-xr-x 2 root root 4096 10-28 14:53 test5[root@localhost test]# cd test5[root@localhost test5]# ll-rw-r--r-- 1 root root 0 10-28 14:46 log5-1.log-rw-r--r-- 1 root root 0 10-28 14:46 log5-2.log-rw-r--r-- 1 root root 0 10-28 14:46 log5-3.log-rw-r--r-- 1 root root 0 10-28 14:53 log.log |
说明:
在没有带-a参数时,两个文件的时间是不一样的。在带了-a参数时,两个文件的时间是一致的。
实例二:目标文件存在时,会询问是否覆盖
命令:
1 | cp log.log test5 |
输出:
12345678910 | [root@localhost test]# cp log.log test5cp:是否覆盖“test5/log.log”? n[root@localhost test]# cp -a log.log test5cp:是否覆盖“test5/log.log”? y[root@localhost test]# cd test5/[root@localhost test5]# ll-rw-r--r-- 1 root root 0 10-28 14:46 log5-1.log-rw-r--r-- 1 root root 0 10-28 14:46 log5-2.log-rw-r--r-- 1 root root 0 10-28 14:46 log5-3.log-rw-r--r-- 1 root root 0 10-28 14:48 log.log |
说明:
目标文件存在时,会询问是否覆盖。这是因为cp是cp -i的别名。目标文件存在时,即使加了-f标志,也还会询问是否覆盖。
实例三:复制整个目录
命令:
输出:
目标目录存在时:
12345678910111213 | [root@localhost test]# cp -a test3 test5 [root@localhost test]# ll-rw-r--r-- 1 root root 0 10-28 14:48 log.logdrwxr-xr-x 6 root root 4096 10-27 01:58 scfdrwxrwxrwx 2 root root 4096 10-28 14:47 test3drwxr-xr-x 3 root root 4096 10-28 15:11 test5[root@localhost test]# cd test5/[root@localhost test5]# ll-rw-r--r-- 1 root root 0 10-28 14:46 log5-1.log-rw-r--r-- 1 root root 0 10-28 14:46 log5-2.log-rw-r--r-- 1 root root 0 10-28 14:46 log5-3.log-rw-r--r-- 1 root root 0 10-28 14:48 log.logdrwxrwxrwx 2 root root 4096 10-28 14:47 test3 |
目标目录不存在是:
12345678 | [root@localhost test]# cp -a test3 test4[root@localhost test]# ll-rw-r--r-- 1 root root 0 10-28 14:48 log.logdrwxr-xr-x 6 root root 4096 10-27 01:58 scfdrwxrwxrwx 2 root root 4096 10-28 14:47 test3drwxrwxrwx 2 root root 4096 10-28 14:47 test4drwxr-xr-x 3 root root 4096 10-28 15:11 test5[root@localhost test]# |
说明:
注意目标目录存在与否结果是不一样的。目标目录存在时,整个源目录被复制到目标目录里面。
实例四:复制的 log.log 建立一个连结档 log_link.log
命令:
1 | cp -s log.log log_link.log |
输出:
12345678 | [root@localhost test]# cp -s log.log log_link.log[root@localhost test]# lllrwxrwxrwx 1 root root 7 10-28 15:18 log_link.log -> log.log-rw-r--r-- 1 root root 0 10-28 14:48 log.logdrwxr-xr-x 6 root root 4096 10-27 01:58 scfdrwxrwxrwx 2 root root 4096 10-28 14:47 test3drwxrwxrwx 2 root root 4096 10-28 14:47 test4drwxr-xr-x 3 root root 4096 10-28 15:11 test5 |
说明:
那个 log_link.log 是由 -s 的参数造成的,建立的是一个『快捷方式』,所以您会看到在文件的最右边,会显示这个文件是『连结』到哪里去的!
来源: