Renaming and moving files & directories
The mv command does both
The basics
The only trick to renaming and moving files under Linux is that they are one and the same action. The command line handles both via the mv
command, which stands for “move”:
mv file1 file2
mv dir/ newdir/
mv /tmp/notes ~/mynotes
mv one two three four five/
In the simplest case, you can rename a file that is currently called foo
, in the current directory, to bar
, with the following command:
mv foo bar
⚠️ Be careful: if bar
already exists, this will overwrite it.
Likewise, you can rename a directory:
mv docs/ notes/
You can omit the trailing slash, although it’s good practice to use it, at least when you’re starting out.
You can use absolute or relative filenames as part of a mv
command. For example, here’s how to move a file to your current directory:
mv /Users/bobby/projects/testing/README.md .
If the final argument is an existing directory, as in the previous example, mv
will move the file there while maintaining its filename. You can even move several files at once using this format:
mv main.c main.h sub.c sub.h src/
This works particularly well with wildcards:
mv *.c *.h src/
Extras
mv
is a very simple command, but there a couple of advanced uses that may come in handy.
First off, if you don’t want mv to overwrite any existing files, use either the -n
(don’t overwrite) or -i (interactive prompt) options. These work well with wildcards and multiple files, some of which may move successfully, while some may not:
Sometimes, you’ll want a quick report of what mv
just did, especially if existing files have been overwritten. The -v
(verbose) option will tell you exactly what happens: