Moving, Renaming, and Copying Files: mv and cp

mv

There are two cases in which you're going to need mv: One is that a file is in the wrong directory. The other is that the file itself has the wrong name.

Suppose you've decided that hello.txt doesn't really belong in your notes directory.

In this example, we say "move hello.txt up one directory level".

Instead of using .., we could have specified /home/pi. It's just faster to type a couple of dots. It would have been even faster to type ~.

Now suppose you've decided that hello.txt itself is called the wrong thing, and should be hello_world.txt instead.

Remember that a directory is just a special kind of file. mv will work to move entire directories just the same as individual files.

moving files can overwrite other files

Always make sure you're not going to overwrite something important when you move a file. There are a couple of good flags to know in order to avoid this:

mv -i

For interactive - mv will ask what you want to do before overwriting any files.

mv -n

For "no clobber". Will skip overwriting any files.

mv -b

Make a backup of any files that get replaced.

cp

In order to duplicate a file, use cp:

Trying to copy a directory, however, behaves oddly:

By default, cp skips over directories. Why? Well, there's some good discussion about this over on Stack Exchange, but the short answer is probably that copying everything in a directory could be a very expensive operation. (Imagine if a directory contained many thousands of files.)

In order to copy a directory, we need to give cp the -r flag to enable recursion. This is part of a broader pattern: In order for many commands to work on entire directories full of files, recursive operations must be specified with a flag, usually -r or -R.

copying files can overwrite other files

As with mv, always make sure you're not going to clobber anything important by copying over it. The -i, -n, and -b flags work here too.

This guide was first published on Jan 13, 2015. It was last updated on Jan 13, 2015. This page (Moving, Renaming, and Copying Files: mv and cp) was last updated on Aug 19, 2019.