How to copy file and directory in Linux. In this tutorial, i’ll explain how to copy file and directory from one location to another using cp command.
How to Copy File and Directory in Linux using CP Command
In Linux cp command is used to copy files and directories.
Syntax for cp is –
cp source destination
* Source represents source file and directory name.
* Destination is where you want to copy file and directory.
Let’s understand this through example. I have one file dummy.txt in /var/www directory. I want to copy this file in new location /var/www/learn.
cp /var/www/dummy.txt /var/www/learn/
We have copied single file. Let’s copy multiple files from one location to another.
cp /var/www/dummy1.txt /var/www/dummy2.txt /var/www/learn
How to Copy Directory using cp command
We learned how to copy single and multiple files from one location to another. Let’s check how to copy directory from one location to another.
Let’s create one dummy directory dummycopy (mkdir dummycoy) in /var/www/. In this directory create two files dummy1.txt and dummy2.txt. Let’s move this directory to new location /var/www/learn .
# Wrong way to copy directory .
cp /var/www/dummycopy /var/www/learn/
I got following error cp: omitting directory `dummycopy/’.
Reason for this error :
By default cp command copy only files. If you want to copy directory use the -r or -R switch which means “recursive” .
cp -r /var/www/dummycopy /var/www/learn/dummycopy/
If you want to explore more about cp command and it’s switches. Use cp manual.
It opens up a manual for cp command.
I’ll try my best to explain cp command and their usage. If you want to add something, please let us know through your comments.