cp command
The cp command is used to copy one or more source files or source directories to the specified file or directory.
grammar
cp [OPTION]… [-T] SOURCE DEST
cp [OPTION]… SOURCE… DIRECTORY
cp [OPTION]… -t DIRECTORY SOURCE…
Common options
-i: interactive
-r, -R: recursively copy the directory and everything inside;
-a: archive, equivalent to -dR --preserv=all
-d: --no-dereference --preserv=links
--preserv[=ATTR_LIST]
-p: --preserv=mode,ownership,timestamp
-v: --verbose: show detailed information when copying
-f: --force: force
Example
The source is a file:
* If the target does not exist, a new target file will be created and the source content will be filled into the target file
[root@ming ~]# touch a.txt
[root@ming ~]# cp a.txt cptest/b.txt
[root@ming ~]# ls cptest/
b.txt
- 1
- 2
- 3
- 4
* The target is an existing file, the source content will be overwritten to the target file
[root@ming ~]# cp a.txt cptest/b.txt
cp: overwrite ‘cptest/b.txt’? y
- 1
- 2
Why is it prompted to overwrite here? This is because of command aliases, -i means interactive, if you don't want to prompt, use backslashes at the beginning of the directory
[root@ming ~]# alias
alias cp='cp -i'
[root@ming ~]# \cp a.txt cptest/b.txt
- 1
- 2
- 3
* If the target is a directory, a new file with the same name as the source will be created in the target directory, and the content of the source will be filled into the new file
[root@ming ~]# touch c.txt
[root@ming ~]# cp c.txt cptest/
[root@ming ~]# ls cptest/
c.txt
- 1
- 2
- 3
- 4
* If the source is multiple files, the target must be a directory and exist, otherwise it is an error
The source is a directory: you need to use the -r option, which means recursive
* If the target does not exist, the specified directory will be created, which can only be a single source directory
[root@ming ~]# mkdir aa
[root@ming ~]# ll
total 4
drwxr-xr-x 2 root root 4096 Dec 27 13:44 aa
[root@ming ~]# cp -r aa ./bb 此目录下没有bb文件夹但是会创建
[root@ming ~]# ls
aa bb
[root@ming ~]# cp -r aa bb ./cc 多个源目录时目标必须要存在,否则拷贝失败
cp: target ‘./cc’ is not a directory
[root@ming ~]#
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
* If the target exists and it is a file, an error will be reported. Even if you think with your feet, it is impossible to put everything in the directory into a file.
* If the target exists and is a directory, all files and directories under the source will be copied to the target.