Working with files
Linux commands: mv
Learn how the Linux mv command moves a file to a new path, how it doubles as the way you rename files, and how to move several files into a folder at once.
Once you have a file, you can move it around using the mv command. You specify the file’s current path, and its new path:
touch pear
mv pear new_pear
The pear file is now called new_pear. There is no separate rename command in UNIX: this is how you rename files and folders.
When the last argument is a folder, mv moves the files into it. You can pass as many files as you want:
touch pear
touch apple
mkdir fruits
mv pear apple fruits/
Both files are now inside fruits. Run ls fruits and you’ll see apple and pear.
If the source doesn’t exist, mv tells you and does nothing:
mv pear new_pear
mv: rename pear to new_pear: No such file or directory
Notice the word “rename” in the message. Within the same disk, mv doesn’t copy any data. It just changes the name or the folder the file is listed in, so moving a 10 GB file takes an instant. Across two disks, the shell has to copy every byte and then delete the original, which is slower and can fail halfway if the disk fills up.
Now the risk. If new_pear already exists, plain mv replaces it without asking, and the old content is gone. When I move files by hand I add -i so it asks first:
mv -i pear new_pear
overwrite new_pear? (y/n [n])
mv -n never overwrites: if the destination exists, it skips the move.
Quote paths with spaces, and put -- before names that start with a dash, so mv doesn’t read them as options:
mv -- "draft report.md" "final report.md"
After a move I like to check both sides. This prints nothing when everything went as expected:
test ! -e pear && test -e fruits/pear
One subtle thing about UNIX: moving a file that a program has open doesn’t stop that program from using it. The program holds a handle to the file itself, not to its name. This is why rotating log files and deploying new versions of an app take some care.
Try this: move a big file inside the same folder and time it, then move it to a USB drive or another disk. The first is instant, the second takes as long as a copy.
This command works on Linux, macOS, WSL, and anywhere you have a UNIX environment
Lesson completed