Copy files in the Linux terminal |

Copy files in the Linux terminal

Use the cp command to copy files in the Linux terminal.

Copying files
Image credits : 

CC BY-SA Seth Kenlon


Subscribe now

Get the highlights in your inbox every week.

To copy a file on a computer with a graphical interface, you usually either drag and drop a file from one window to another window, sometimes using a modifier key. Alternately, you might prefer to right-click on a file icon, select Copy, and then Paste the file icon into another window.

To copy a file in a terminal, you use the cp command, which works exactly like the mv command, except that it duplicates the contents of a file rather than moving them from one location to another.

$ cp example.txt ~/Documents

As with the mv command, you can rename a file while copying it.

$ cp example.txt ~/Documents/file.txt

Be careful when using cp, because it does exactly what you tell it to do. By default, it does not ask you whether you want to copy one file over another file with the same name. To protect yourself from this, use cp --interactive (or -i for short), which runs cp in interactive mode, meaning that it will ask you whether you're sure you want to overwrite an existing file. You can either confirm or cancel and re-do the cp and rename the file to something different so that it doesn't conflict with existing files.

Copy a folder

The cp command looks for files, not folders because folders don't really exist (that is, they're not really data, they're just markers for us humans to logically divide our data into different imaginary containers.) To copy a folder, use cp --recursive (or -r for short), which takes the files in the folder and recreates their imaginary container.

$ cp -r Documents MyStuff
$ ls

You may notice that the Linux shell is eerily quiet when it works. This is actually by design. How many times have you set a computer on a task, like copying a thousand files from one drive to another, only to come back 4 hours later to find that it stopped copying after the first file, just to ask you some trivial esoteric question?

Sometimes, however, it's nice to have some feedback from your OS. Usually, the -v switch adds "verbosity" to the command:

$ cp -r --verbose Documents Stuff
'Documents/' -> 'Stuff'
'Documents/example.txt' -> 'Stuff/example.txt'
'Documents/file.txt' -> 'Stuff/file.txt'
'Documents/example.png' -> 'Stuff/example.png'
'Documents/picture.png' -> 'Stuff/picture.png'

Moving files

Use the mv command to move a file from one location to another.
rename files

To rename a file in the terminal, move the file with mv from itself to itself with a new name. Here's an example.

About the author

Seth Kenlon
Seth Kenlon - Seth Kenlon is a UNIX geek, free culture advocate, independent multimedia artist, and D&D nerd. He has worked in the film and computing industry, often at the same time. He is one of the maintainers of the Slackware-based multimedia production project Slackermedia.