Linux cp command with examples

In this article, we will see Linux cp command with examples. Linux cp stands for copy and it is used to copy files or group of files or directory.

Linux cp Syntax:

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

Linux cp command examples:

1. Basic copy operation. It is simply copying a file to source directory.

r2schools@mongodb1:~/linux$ ls aa.txt ab.sql logs scripts tt.csh abcd.ssh dumps r2schools.py tt.c tt.py

Copy file aa.txt to the directory logs.

cp aa.txt logs/

Lets verify file is copied or not by using following command.

ls logs/

Linux cp command with examples

2. -i. If the destination where you are copying the file already contains a file of same name, then the cp command silently overwrites the existing file. This can be done by running cp in interactive mode, which is enabled using the -i option.

r2schools@mongodb1:~/linux$ cp -i aa.txt ab.sql scripts/ cp: overwrite 'scripts/aa.txt'? yes cp: overwrite 'scripts/ab.sql'? yes

3. -r or R. To copy a directory from one place to another use -r or -R option in cp command.
without -r error will be thrown like below.
Linux cp command with examples

r2schools@mongodb1:~/linux$ cp -r logs dumps/ r2schools@mongodb1:~/linux$ ls dumps logs

4. Copy similar files to another directory. Here we are copying .py files to scripts directory using below command.

cp *.py scripts/