Moving and Renaming Files

Here's something that confused me when I started: moving and renaming are the same command.

hljs bash
mv oldname newname    # Rename
mv file directory/    # Move

Same command, different effects based on context.

Renaming Files

Terminal
$ls
oldname.txt
$mv oldname.txt newname.txt
$ls
newname.txt

The old file is gone. The new file is the same data with a different name.

Moving Files

Terminal
$ls
file.txt Documents/
$mv file.txt Documents/
$ls
Documents/
$ls Documents/
file.txt

Moving Multiple Files

Terminal
$mv file1.txt file2.txt file3.txt archive/
$ls archive/
file1.txt file2.txt file3.txt

When moving multiple items, the last argument must be a directory.

Move and Rename

Terminal
$mv ~/Downloads/document.pdf ~/Documents/report.pdf

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:

Terminal
$mv old_project/ new_project/
$mv folder/ /tmp/

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:

Terminal
$mv -i newfile.txt existing.txt
mv: overwrite 'existing.txt'? n

-n (No Clobber)

Never overwrite:

Terminal
$mv -n source.txt destination.txt
(does nothing if destination exists)

-v (Verbose)

Show what's happening:

Terminal
$mv -v file.txt Documents/
renamed 'file.txt' -> 'Documents/file.txt'

-b (Backup)

Create a backup before overwriting:

Terminal
$mv -b newconfig.txt config.txt
$ls
config.txt config.txt~

The ~ file is the old version.

Dangerous Behavior

mv Overwrites Silently

By default, mv will overwrite the destination without asking:

hljs bash
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

hljs bash
mv log.txt log_$(date +%Y%m%d).txt

Move to Archive

hljs bash
mv *.log archive/
mv old_* trash/

Rename Extension

hljs bash
mv file.txt file.md

Organize Downloads

hljs bash
mv ~/Downloads/*.pdf ~/Documents/PDFs/
mv ~/Downloads/*.jpg ~/Pictures/

mv vs cp: When to Use Which

SituationCommand
Need original to staycp
Just relocating/renamingmv
Creating a backupcp
Reorganizingmv
Knowledge Check

What happens if you `mv file.txt` to a filename that already exists?

Key Takeaways

  • mv both moves AND renames (same operation)
  • No -r needed for directories
  • mv overwrites silently by default - use -i to be safe
  • -b creates backup before overwriting
  • mv is instant on same filesystem (just updates directory entry)

Next: the dangerous one - deleting files.