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 /tmpdirectory 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: