Moving and Renaming Files
Here's something that confused me when I started: moving and renaming are the same command.
mv oldname newname # Rename
mv file directory/ # Move
Same command, different effects based on context.
Renaming Files
The old file is gone. The new file is the same data with a different name.
Moving Files
Moving Multiple Files
When moving multiple items, the last argument must be a directory.
Move and Rename
Move to a different location AND give it a new name in one command.
Moving Directories
Unlike cp, mv doesn't need special flags for directories:
Directories move just like files.
Why No -r Needed?
mv just updates the directory entry - it doesn't actually copy data byte by byte. That's why it's instant even for huge directories (as long as they stay on the same filesystem).
Useful Flags
-i (Interactive)
Prompt before overwriting:
-n (No Clobber)
Never overwrite:
-v (Verbose)
Show what's happening:
-b (Backup)
Create a backup before overwriting:
The ~ file is the old version.
Dangerous Behavior
mv Overwrites Silently
By default, mv will overwrite the destination without asking:
mv important.txt different.txt
# If different.txt existed, it's gone forever
Use -i if you're not sure.
Common Patterns
Rename with Timestamp
mv log.txt log_$(date +%Y%m%d).txt
Move to Archive
mv *.log archive/
mv old_* trash/
Rename Extension
mv file.txt file.md
Organize Downloads
mv ~/Downloads/*.pdf ~/Documents/PDFs/
mv ~/Downloads/*.jpg ~/Pictures/
mv vs cp: When to Use Which
| Situation | Command |
|---|---|
| Need original to stay | cp |
| Just relocating/renaming | mv |
| Creating a backup | cp |
| Reorganizing | mv |
What happens if you `mv file.txt` to a filename that already exists?
Key Takeaways
mvboth moves AND renames (same operation)- No
-rneeded for directories mvoverwrites silently by default - use-ito be safe-bcreates backup before overwritingmvis instant on same filesystem (just updates directory entry)
Next: the dangerous one - deleting files.