Linux mv command examples

The Linux mv command lets you move one or more files or directories. Since it's very similar to the cp command, I'll move through this post quickly.

Basic Linux mv examples

To rename a file currently named "foo" to a new file named "bar" just type:

mv foo bar

Although it's called the Linux mv command, it's commonly used to rename files.

To move a file named "foo" to the /tmp directory type:

mv foo /tmp

To move a file named "foo" to a new file named "bar" in the /tmp directory type:

mv foo /tmp/bar

Conversely, if the file "foo" is in the /tmp directory, and you want to move it to the current directory you'd type this:

mv /tmp/foo .

No matter where you are in the filesystem, if you want to move the same file to your home directory you can type this:

mv /tmp/foo ~

The ~ character is a shortcut character that refers to your home directory (and works with all shell commands, not just the mv command). To move the same file to a directory named "dir1" in your home directory you could type this:

mv /tmp/foo ~/dir1

More complicated mv examples

To move several files named "foo1", "foo2", and "foo3" into a directory named "dir1", use a mv command like this:

mv foo1 foo2 foo3 dir1

That's the long way to type it out. This command does this same thing:

mv foo[123] dir1

And if you don't have any other file beginning with the string "foo" you can just take this shortcut:

mv foo* dir1

How to move directories

Assuming that you have a directory named "dir1" that you want to rename to "dir2" you can use a command like this:

mv dir1 dir2

Don't clobber existing files

The mv command has several options to keep you from clobbering existing files during copy operations. The -i option prompts you before performing a move operation that would overwrite an existing file. Assuming that "bar" is a file that already exists, the interaction looks something like this:

/Users/al/yada> mv -i foo bar 
overwrite bar? (y/n [n]) n
not overwritten

In this example the system prompted me with the overwrite bar? (y/n) prompt, and I responded with n.

Instead of using -i you can use -n, which just doesn't allow this to happen at all. Unfortunately it doesn't give you any output, unless you also use the -v option, like this:

/Users/al/yada> mv -nv foo bar
bar not overwritten

mv aliases

Because of the potential danger of clobbering existing files a lot of people create an alias for the mv command, like this:

alias mv="mv -i"

As with the cp command I don't see any harm in doing this, and you can always undo it, so I highly recommend it.