Intro To 'cp' Command In Linux
2023-04-22 - By Robert Elder
I use the 'cp' command to copy files on my computer:
cp cat.jpg cat_copy1.jpg
I also use it to make copies of entire directories. If I try to make a copy of the directory 'all-photos' like this:
cp all-photos photos-backup-copy
I'll see an error message like this:
cp: -r not specified; omitting directory 'all-photos'
To copy directories, I need to use the '-r' flag:
cp -r all-photos photos-backup-copy
I can also use the '-p' flag to preserve permission and ownership information on the copied file:
ls -l
If we start with this file:
-rw-rwxr-- 1 mike mike 1048576 Apr 23 21:35 dog.jpg
and run these two copy commands:
cp dog.jpg dog_copy1.jpg
sudo cp -p dog.jpg dog_copy2.jpg
and then re-run the ls command:
ls -l
the output is now this:
-rw-rwxr-- 1 robert robert 1048576 Apr 23 21:38 dog_copy1.jpg
-rw-rwxr-- 1 mike mike 1048576 Apr 23 21:35 dog_copy2.jpg
-rw-rwxr-- 1 mike mike 1048576 Apr 23 21:35 dog.jpg
this illustrates the difference when using the '-p' flag.
If you're not careful, you can overwrite an existing file when making a copy:
ls -l
total 1024
-rw-rwxr-- 1 robert robert 1048576 Apr 23 21:38 dog_copy1.jpg
-rw-rw-r-- 1 robert robert 0 Apr 23 21:45 empty.txt
cp empty.txt dog_copy1.jpg
ls -l
total 0
-rw-rwxr-- 1 robert robert 0 Apr 23 21:46 dog_copy1.jpg
-rw-rw-r-- 1 robert robert 0 Apr 23 21:45 empty.txt
As you can see above, the 'dog_copy1.jpg' file has been overwritten with the 'empty.txt' and the original data has been lost.
That's why I use the '-n' flag to prevent this from happening:
ls -l
total 1024
-rw-rwxr-- 1 robert robert 1048576 Apr 23 21:38 dog_copy1.jpg
-rw-rw-r-- 1 robert robert 0 Apr 23 21:45 empty.txt
cp -n empty.txt dog_copy1.jpg
ls -l
total 1024
-rw-rwxr-- 1 robert robert 1048576 Apr 23 21:47 dog_copy1.jpg
-rw-rw-r-- 1 robert robert 0 Apr 23 21:45 empty.txt
And that's why the 'cp' command is my favourite Linux command.
![]() A Surprisingly Common Mistake Involving Wildcards & The Find Command
Published 2020-01-21 |
![]() $20.00 CAD |
![]() A Guide to Recording 660FPS Video On A $6 Raspberry Pi Camera
Published 2019-08-01 |
![]() The Most Confusing Grep Mistakes I've Ever Made
Published 2020-11-02 |
![]() Use The 'tail' Command To Monitor Everything
Published 2021-04-08 |
![]() Using A Piece Of Paper As A Display Terminal - ed Vs. vim
Published 2020-10-05 |
![]() An Introduction To Data Science On The Linux Command Line
Published 2019-10-16 |
![]() An Overview of How to Do Everything with Raspberry Pi Cameras
Published 2019-05-28 |
Join My Mailing List Privacy Policy |
Why Bother Subscribing?
|