一、用法

  该命令用于将一个或者多个文件或者目录复制到指定的目的文件或者目录,它可以将单个源文件复制成一个指定文件名的具体的文件或一个已经存在的目录下。当一次复制多个文件时,目标文件参数必须是一个已经存在的目录,否则将出现错误。

常见参数详解:

       -a, --archive
              same as -dR --preserve=all #相当于-pdr

       -d     same as --no-dereference --preserve=links #若源文件为链接文件,则复制链接文件属性而非文件本身

       -f, --force #强制复制,如果目标文件已经存在且无法打开,则移除后再尝试
              if  an  existing  destination file cannot be opened, remove it and try
              again (this option is ignored when the -n option is also used)

       -i, --interactive #若目标文件已经存在,覆盖文件之前先询问用户
              prompt before overwrite (overrides a previous -n option)

       -p     same as --preserve=mode,ownership,timestamps #连源文件或目录的属性一起复制过去

       -R, -r, --recursive  #递归的复制目录
              copy directories recursively

       -u, --update #若目标文件存在,当源文件比目标文件新时才复制或者目标文件丢失
              copy only when the SOURCE file is newer than the destination  file  or
              when the destination file is missing

二、实战

# 将test文件夹中的文件全部拷贝到test2
[root@localhost project]# cp -a ./test1/* ./test2/
[root@localhost project]# ll ./test2
total 0
-rw-r--r--. 1 root root 0 Oct 10 20:45 t1.txt
-rw-r--r--. 1 root root 0 Oct 10 20:45 t2.txt

#拷贝已经存在的文件先询问
[root@localhost test1]# cp -i t1.txt ../test2/
cp: overwrite ‘../test2/t1.txt’?

#递归拷贝
[root@localhost project]# cp -r test1 ./test2/
02-14 02:36