Linux 下cp 命令整理
用法:
cp [选项]... [-T] 源文件 目标文件
或:cp [选项]... 源文件... 目录
或:cp [选项]... -t 目录 源文件...
将源文件复制至目标文件,或将多个源文件复制至目标目录。
长选项必须使用的参数对于短选项时也是必需使用的。
-a, --archive 等于-dR --preserve=all
--backup[=CONTROL 为每个已存在的目标文件创建备份
-b 类似--backup 但不接受参数
--copy-contents 在递归处理是复制特殊文件内容
-d 等于--no-dereference --preserve=links
-f, --force 如果目标文件无法打开则将其移除并重试(当 -n 选项
存在时则不需再选此项)
-i, --interactive 覆盖前询问(使前面的 -n 选项失效)
-H 跟随源文件中的命令行符号链接
-l, --link 链接文件而不复制
-L, --dereference 总是跟随符号链接
-n, --no-clobber 不要覆盖已存在的文件(使前面的 -i 选项失效)
-P, --no-dereference 不跟随源文件中的符号链接
-p 等于--preserve=模式,所有权,时间戳
--preserve[=属性列表 保持指定的属性(默认:模式,所有权,时间戳),如果
可能保持附加属性:环境、链接、xattr 等
-c same as --preserve=context
--sno-preserve=属性列表 不保留指定的文件属性
--parents 复制前在目标目录创建来源文件路径中的所有目录
-R, -r, --recursive 递归复制目录及其子目录内的所有内容
--reflink[=WHEN] 控制克隆/CoW 副本。请查看下面的内如。
--remove-destination 尝试打开目标文件前先删除已存在的目的地
文件 (相对于 --force 选项)
--sparse=WHEN 控制创建稀疏文件的方式
--strip-trailing-slashes 删除参数中所有源文件/目录末端的斜杠
-s, --symbolic-link 只创建符号链接而不复制文件
-S, --suffix=后缀 自行指定备份文件的后缀
-t, --target-directory=目录 将所有参数指定的源文件/目录
复制至目标目录
-T, --no-target-directory 将目标目录视作普通文件
-u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing
-v, --verbose explain what is being done
-x, --one-file-system stay on this file system
-Z, --context=CONTEXT set security context of copy to CONTEXT
--help 显示此帮助信息并退出
--version 显示版本信息并退出
主要参数范例:
范例一:-a
将.bash_profile 复制到/tmp 下改名为bash_profile
[root@test ~]# cp /root/.bash_profile /tmp/bash_profile
然后分别查看这两个文件的属性
[root@test tmp]# ls -l bash_profile
-rw-r--r--. 1 root root 176 3 月 23 22:02 bash_profile
[root@test ~]# ls -l .bash_profile
-rw-r--r--. 1 root root 176 5 月 20 2009 .bash_profile
可以看出,文件的属性是不一样的。那么加上-a 参数,再看看效果
[root@test ~]# cp /root/.bash_profile /tmp/bash_profile
然后分别查看这两个文件的属性
[root@test tmp]# ls -l bash_profile
-rw-r--r--. 1 root root 176 5 月 20 2009 .bash_profile
[root@test ~]# ls -l .bash_profile
-rw-r--r--. 1 root root 176 5 月 20 2009 .bash_profile
可以看出加上-a 参数之后,文档的所有属性都会一样!
范例二:-i -f
将.bash_profile 复制到/tmp 下改名为bash_profile
[root@test ~]# cp /root/.bash_profile /tmp/bash_profile
重新执行上述命令,加上-i
[root@test ~]# cp -i /root/.bash_profile /tmp/bash_profile
cp:是否覆盖"/tmp/bash_profile"? y
You have new mail in /var/spool/mail/root
在执行覆盖之前会询问,如果不需要询问,则用-f 强制覆盖。
范例三:-r
需要将/etc 下的httpd 目录中的所有文件复制到/tmp
[root@test /]# cp -r /etc/httpd/ /tmp/
范例四:-u 上述案例二中,如果我们需要根据.bash_profile 是否更新来判断是否复制,则需
要-u 参数
[root@test ~]# cp �u /root/.bash_profile /tmp/bash_profile
范例五:复制多个文件
需要将/root/.bash_profile /root/.bashrc 多个文件复制到tmp
[root@test ~]# cp /root/.bash_profile /root/.bashrc /tmp