Copy files and directories using the CP command in Linux

Home > Search > Linux commands
  by

The cp (copy) command can be used to copy a file or directory from one location to another location.


Copy file

In this example, file1 is copied from /home/john.doe to /tmp.

~]# cp /home/john.doe/file1 /tmp

 

When only the target directory is provided, the new file will have the same name as the original file. In this example, File1 will not reside in both the /home/john.doe to /tmp directories.

~]# ls /home/john.doe
file1

~]# ls /tmp
file1

 

When the target directory and new file name is provided, the new file will have the new file name. In this example, file1 is copied and a new file named file2 is created.

~]# cp /home/john.doe/file1 /tmp/file2

~]# ls /home/john.doe
file1

~]# ls /tmp
file2

 


Copy directory

The cp command with the -r (recursive) command can be used to copy a directory from one location to another. The -r option must be used to copy all of the files and folders in the directory. In this example, directory1 is copied to the /tmp folder.

~]# cp -r /home/john.doe/directory1 /tmp

 


Change file name

The cp command followed by the current file name and then a new file name can be used to create a new file with a different name. In this example, file1 is copied and renamed to file2. This can be dangerous. If file2 already exists, file2 will be overwritten with no prompt or warning. 

[john.doe@server1 ~]# cp file1 file2

 

Both file1 and file2 will now reside in the directory. 

[john.doe@server1 ~]# ls /home/john.doe
file1 file2

 


Interactive prompt

The -i or --interactive option can be used to display an interactive prompt. The interactive prompt can prevent a file from being overwritten. In this example, a file named file1 already exists in both the /home/john.doe to /tmp directories. When attempting to copy file1 from /home/john.doe to /tmp, a prompt appears.

[john.doe@server1 ~]# cp /home/john.doe/file1 /tmp
cp: overwrite '/tmp/file1'?

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments