Skip to content

Linux Foundations / Find your way around Linux ยท Step 22 of 63

Lesson: mv (Move)Switch
โ† Linux Foundations

Shell and files

mv (Move)

Move and rename files and directories with mv, and avoid overwriting by mistake.

mv moves things. It is also how you rename on Linux, because renaming is just moving a file to a new name. The form is mv SOURCE DESTINATION.

Renaming

$ ls
draft.txt
$ mv draft.txt final.txt
$ ls
final.txt

The old name is gone. No second copy exists.

Moving into a directory

If the destination is an existing directory, the file goes inside it:

$ mv final.txt documents/
$ ls documents
final.txt

You can move and rename in one step:

$ mv documents/final.txt ./report.txt

To move several items, put the directory last:

$ mv a.txt b.txt documents/

If you mistype a directory name, mv may simply rename your file to that word. When you are moving a file, adding a trailing / to the destination makes mv report an error if the directory does not exist.

Directories

Unlike cp, mv needs no -r to handle a directory:

$ mv photos pictures

If pictures does not exist, this renames photos. If it does exist, photos is moved inside it.

Overwriting

By default, mv replaces an existing destination file without asking, and there is no undo. Protect yourself with:

  • -i to ask first.
  • -n to never overwrite.
  • -v to print what was done.
$ mv -i new.txt report.txt
mv: overwrite 'report.txt'? n

Some systems alias mv to mv -i, mainly for root.

Across filesystems

Within one filesystem, a move only changes directory entries, so even a huge file moves almost instantly. Moving to a different filesystem, such as a USB drive, requires copying the data and then removing the original. That takes time in proportion to the size.

Practise on safe files in the files and links lab.

Try it

  1. Create old.txt and rename it to new.txt.
  2. Make a directory and move the file into it.
  3. Rename the directory.
  4. Create two files and use mv -i to try overwriting one with the other.

Check your understanding

mv (Move)

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.