Linux cp command tutorial: cp syntax and cp examples

linux cp command – copy files or group of files or directories.

syntax

cp [OPTION]... [-T] SOURCE DEST
cp [OPTION]... SOURCE... DIRECTORY
cp [OPTION]... -t DIRECTORY SOURCE...

Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

options

  • -R, -r, –recursive
    copy directories recursively
  • -f, –force
    if an existing destination file cannot be opened, remove it and try again
  • -p, –preserve[=ATTR_LIST]
    preserve the specified attributes (default: mode, ownership, timestamps), if possible additional attributes: context, links, xattr, all
  • –no-preserve=ATTR_LIST
    don’t preserve the specified attributes
  • –parents
    use full source file name under DIRECTORY
  • -i, –interactive
    prompt before overwrite
  • -v, –verbose
    explain what is being done
  • -u, –update
    copy only when the SOURCE file is newer than the destination file or when the destination file is missing

examples

Copy a file

When copying a file, if the target file [DEST] does not exist, it will be created; But if the target file[DEST] exists, it is simply overwritten without any warning

➜ ls
a.log
➜ cp a.log b.log
➜ ls
a.log  b.log

using option “-i”, copy a file

When the b.log file exists, there will be a warning. If the b.log file does not exist, there will be no warning.

➜ cp -i a.log b.log
cp: overwrite 'b.log'? y
➜ 

Copy multiple files to directory

➜ ls
a.log  b.log  desc_directory
➜ cp a.log b.log desc_directory
➜ ls desc_directory
a.log  b.log

OR

➜ ls
a.log  b.log  desc_directory
➜ ls desc_directory
➜ cp *.log desc_directory
➜ ls desc_directory
a.log  b.log

Copy directory and files in them

➜ cp -r desc_directory new_dir

Keep the characteristics of each file – using option “-p”

The time of the last data modification and the time of the last access, the ownership, and the file permission-bits.

➜ cp -p a.log e.log
➜ ls -l
total 0
-rw-rw-r-- 1 ylspirit ylspirit 0 Nov 23 16:43 a.log
-rw-rw-r-- 1 ylspirit ylspirit 0 Nov 23 17:22 b.log
-rw-rw-r-- 1 ylspirit ylspirit 0 Nov 23 16:43 e.log

Update copy – using option “-u”

Copy only updated or nonexistent files.

➜ cp -u *.log desc_directory

Copy all files and folders in the current directory

➜ cp -R * /tmp

Recommended Posts:

Linux common commands tutorial and use examples
GNU sed syntax and sed examples
Awk tutorial: awk syntax and awk examples
chmod command and chown command usage
iostat command in linux with examples
grep command in linux whith examples
top command in linux with examples

Add a Comment

Your email address will not be published. Required fields are marked *