Linux Command: cp (copy files and directories)

Summary

Command Namecp
UsageCopy files andqq directories
Section / Group User Command

Signature

There are 3 types of signatures we see for “cp” command, depending on the usage-

Signature #1

cp [OPTION]… [-T] SOURCE DEST

Signature #2

cp [OPTION]… SOURCE DIRECTORY

Signature #3

cp [OPTION]… -t DIRECTORY SOURCE…

Usage

Copy files and directories to certain destination.

This command can copy single item to a single destination, or multiple items to a destination.

Notes

Arguments

Here are the arguments used for the command-

ParameterDescriptionOptionalMultiple
OPTIONSOptions and flags for different behavior of the commandTrueTrue
SOURCE
DEST
DIRECTORY

NOTE

  • If the directory already exists then the following message is returned-
    mkdir: cannot create directory ‘sample’: File exists

Here are the options-

OptionDescripitonAlias

Examples

Use the command “cp” to copy files and directories from one location to another.

Copy File

$ cp file1 new_dir/

$ ls -l new_dir/

total 0
-rw-r--r-- 1 bigboxcode bigboxcode 0 Jul 21 04:28 file1
Bash

Copy the Same File Again

$ cp file1 new_dir/

$ ls -l new_dir/

total 0
-rw-r--r-- 1 bigboxcode bigboxcode 0 Jul 21 04:30 file1
Bash

Copy File using Pattern

$ cp file* new_dir/

$ ls -l new_dir/

total 0
-rw-r--r-- 1 bigboxcode bigboxcode 0 Jul 21 04:33 file1
-rw-r--r-- 1 bigboxcode bigboxcode 0 Jul 21 04:33 file2
-rw-r--r-- 1 bigboxcode bigboxcode 0 Jul 21 04:33 file3
Bash

Copy with New Name

$ cp sample_cat_file.txt new_sample_cat_file.txt

$ ls

bigboxfile.txt  d1  file1  file2  file3  new_dir  new_sample_cat_file.txt  sample_cat_file.txt

$ cat sample_cat_file.txt

big
box

code

last line here

$ cat new_sample_cat_file.txt

big
box

code

last line here
Bash

Copy Directory

# Create directory
$ mkdir d1

# Try to copy directory
$ cp d1 new_dir/
cp: -r not specified; omitting directory 'd1'
Bash

The command fails as we are supposed to use the “-r” flag for recursive copying. Let’s try with “-r”

$ cp d1 new_dir/ -r

$ ls -l new_dir/

total 4
drwxr-xr-x 2 bigboxcode bigboxcode 4096 Jul 21 04:38 d1
-rw-r--r-- 1 bigboxcode bigboxcode    0 Jul 21 04:33 file1
-rw-r--r-- 1 bigboxcode bigboxcode    0 Jul 21 04:33 file2
-rw-r--r-- 1 bigboxcode bigboxcode    0 Jul 21 04:33 file3
Bash

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.