mv — Moving Files and Directories
Asha's garden photos keep landing in her home directory, and last month's notes are sitting in the wrong folder. On the command line there is no dragging with a mouse. One command moves things, and the same command renames them.
The rule
mv takes the thing first, then where it goes.
The shape is always:
mv SOURCE DESTINATIONWhat happens depends on the destination:
- If the destination is an existing directory, the source moves into it and keeps its name.
- If the destination does not exist, the source is renamed to that name.
- If the destination is an existing file, it is replaced, silently, with no warning.
$ cd ~/garden
$ mv ../tomato.jpg plots/ # moves into plots, still called tomato.jpg
$ mv notes.txt june-notes.txt # renames in place
$ mv plots beds # renames a whole directoryMoving a directory needs no special option. mv doesn't copy anything; it just changes where the name points, so the whole folder goes along, whatever it contains.
You can move several things at once. When you give more than one source, the last argument must be a directory:
$ mv tomato.jpg basil.jpg chilli.jpg plots/Two safety options are worth learning now:
mv -i(interactive) asks before it overwrites a file that already exists.mv -n(no-clobber) never overwrites. It just skips that file.
The shortcut
Before pressing Enter, ask one question about the last argument: does it already exist, and is it a directory? That single check tells you whether mv will move into, rename, or overwrite.
Look at the last argument
The destination is
archive. Runlsto see whether it exists.
Moving within the same disk is almost instant, even for a folder of thousands of photos, because only the name changes place and the data stays where it is. Moving onto a different disk is slower: mv has to copy everything across and then delete the original.
A trailing slash helps too. Writing mv notes.txt archive/ tells the shell you mean a directory. If archive isn't one, you get an error instead of a surprise rename.
Drills
Answer fast — trust the rule.
In mv a.txt b.txt, which file is the one being moved or renamed?
plots is an existing directory. What does mv tomato.jpg plots do?
Which command moves three photos into plots in one go?
old.txt and new.txt both exist. What does mv old.txt new.txt do by default?
Remember
- mv takes the thing first, then where it goes. The same command moves and renames.
- Check the last argument: an existing directory means "into", a new name means "rename", an existing file means "overwrite".
- mv overwrites silently. Use
-ior-nwhen that matters.
