FreeKB - Copy files and directories using the CP command in Linux
Copy files and directories using the CP command in Linux

Home > Search > Linux commands


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.

Notice the * character is used. If there are any hidden files in the directory, when using the * character, the hidden files will not be copied.

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

 

Notice the . character is used. If there are any hidden files in the directory, when using the . character, the hidden files will be copied.

~]# 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

By default, the cp command is interactive, which means you will be prompted to overwrite the new file is the new file already exists. Since the cp command is interactive by default, even if you do not use the -i or --interactive option, you will be prompted if the new file already exists.

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

 

~]# cp --interactive /home/john.doe/file1 /tmp
cp: overwrite '/tmp/file1'?

 

This occurs because most every user profile on a modern Linux system has the following in their bash profile file.

alias cp='cp -i'

 

The unalias command can be used to temporarily disable the interactive prompt.

unalias cp

 



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 d45f2 in the box below so that we can be sure you are a human.




Comments