You've learned to copy files with cp and create directories with mkdir. Now it's time to master one of the most versatile file management commands in Linux: mv. Unlike copying, which creates duplicates, mv moves files and directoriesโwhich also makes it perfect for renaming them.
Understanding mv is critical for the LFCS exam and daily system administration. Whether you're reorganizing files, renaming configuration files, or moving logs to archive directories, mv is your go-to command.
๐ฏ What You'll Learn:
- Understanding mv syntax and how it differs from cp
- Moving files between directories
- Renaming files and directories in place
- Using mv with directories (no -r needed!)
- Essential mv flags: -i, -v, -n, -u
- Moving multiple files with wildcards
- Safe mv practices and common pitfalls
- Real-world file organization workflows
Series: LFCS Certification - Phase 1 (Post 25 of 52)
Understanding the mv Command
The mv command stands for "move". It performs two closely related operations:
- Moving files/directories from one location to another
- Renaming files/directories (moving them to a new name in the same location)
Key Difference from cp
Unlike cp which creates a copy and leaves the original:
- cp: Creates duplicate, original remains
- mv: Moves the original, nothing left behind
Think of cp as "photocopy" and mv as "cut and paste" in a word processor.
Basic mv Syntax
mv [OPTIONS] SOURCE DESTINATION
Three scenarios:
- Rename:
mv oldname newname(same directory) - Move to directory:
mv file directory/ - Move and rename:
mv file directory/newname
Scenario 1: Renaming Files
The simplest use of mv is renamingโmoving a file to a new name in the same location.
Basic Renaming Example
$ pwd
/tmp/data
$ ls
passwd
$ mv passwd whatever
What happened:
- File
passwdno longer exists - File
whatevernow exists with the exact same content - No copying occurredโthe file was simply renamed
- Timestamps, permissions, ownership remain unchanged
$ ls
whatever
Renaming is Instant
Unlike copying, renaming (on the same filesystem) is instant regardless of file size:
- cp: Reads entire file, writes new copy (slow for large files)
- mv: Updates filesystem metadata only (instant)
# This takes seconds for a 1GB file
cp largefile.iso largefile-copy.iso
# This is instant for a 1GB file
mv largefile.iso largefile-renamed.iso
๐ก Renaming is just moving within the same directoryโthat's why the same command handles both operations!
Scenario 2: Moving Files Between Directories
Move files from one directory to another while keeping the same name.
Moving to Parent Directory
$ pwd
/tmp/data
$ ls
whatever
$ mv whatever ..
$ ls
# Empty - whatever is gone
$ ls ..
# ... whatever appears here
The .. (parent directory) is the destination. The file keeps its name whatever.
Moving with Absolute Paths
$ mv /tmp/data/file.txt /home/centos9/documents/
What happens:
/tmp/data/file.txtdisappears/home/centos9/documents/file.txtappears- Same content, same permissions, same timestamps
Moving to Current Directory
$ pwd
/tmp/data
$ mv /etc/passwd .
mv: cannot move '/etc/passwd' to './passwd': Permission denied
Why it failed: You don't have permission to modify /etc/passwd. Even though you can read it and copy it, moving requires write permission to the source directory (/etc), which you don't have.
โ ๏ธ mv requires write permission to the source directory because it's removing the file from there. This is different from cp, which only needs read permission on the source.
Scenario 3: Moving Directories
Unlike cp, which requires the -r flag for directories, mv works on directories without any special flag.
Moving a Directory
$ mkdir project
$ touch project/file1.txt project/file2.txt
$ mv project /tmp/archive/
$ ls project
ls: cannot access 'project': No such file or directory
$ ls /tmp/archive/
project
What happened:
- The entire
projectdirectory moved - All contents moved with it
- No
-rflag needed - Instant operation (just updates filesystem metadata)
Why No -r Flag?
When you mv a directory:
- The directory's entry in the filesystem is updated
- The contents aren't touched individually
- It's a metadata operation, not a recursive copy
Compare to cp -r:
- Copies each file individually
- Creates new directory
- Processes entire tree recursively
Moving Multiple Files
Like cp, you can move multiple files to a destination directory.
Multiple Files to Directory
$ mv file1.txt file2.txt file3.txt documents/
Requirements:
- All arguments except the last are SOURCE files
- Last argument must be an existing directory
- All sources move to that directory
Using Wildcards
$ sudo mv /tmp/files/[ab]* /tmp/files/photos/
What happens:
- All files starting with
aorbmove tophotos/ - Sources disappear from
/tmp/files/ - They reappear in
/tmp/files/photos/
Real example from system:
$ ls /tmp/files/
accountsservice alsa appstream.conf ... photos pictures videos
$ sudo mv /tmp/files/[ab]* /tmp/files/photos/
$ sudo mv /tmp/files/c* /tmp/files/videos/
$ ls /tmp/files/photos/
accountsservice aliases alternatives appstream.conf asound.conf audit ...
๐ก Remember: wildcards are expanded by the shell before mv runs. The mv command sees a list of files, not the wildcard pattern.
Essential mv Options
Option 1: Interactive Mode (-i)
Prompt before overwriting any existing file.
$ touch important.txt backup.txt
$ mv -i backup.txt important.txt
mv: overwrite 'important.txt'? n
Safety check:
-i= interactive- Prompts before any overwrite
- Answer
yto proceed,nto cancel - Recommended for important files
Option 2: Verbose Mode (-v)
Show what's being moved.
$ mv -v file1.txt documents/
renamed 'file1.txt' -> 'documents/file1.txt'
$ mv -v *.txt archive/
renamed 'file1.txt' -> 'archive/file1.txt'
renamed 'file2.txt' -> 'archive/file2.txt'
renamed 'file3.txt' -> 'archive/file3.txt'
Useful for:
- Confirming operations
- Debugging scripts
- Seeing what's happening with wildcards
Option 3: No Clobber (-n)
Never overwrite existing files.
$ echo "original" > important.txt
$ echo "backup" > backup.txt
$ mv -n backup.txt important.txt
# Nothing happens - important.txt exists
$ cat important.txt
original
Behavior:
-n= no clobber (don't overwrite)- Silently refuses to overwrite
- Original file remains unchanged
- Safer than -i for scripts (no prompt needed)
Option 4: Update (-u)
Only move if source is newer than destination, or destination doesn't exist.
$ touch old.txt
$ sleep 2
$ touch new.txt
$ ls -l
-rw-r--r--. 1 centos9 centos9 0 Nov 1 10:00 old.txt
-rw-r--r--. 1 centos9 centos9 0 Nov 1 10:02 new.txt
$ mv -u new.txt old.txt # Overwrites (new is newer)
$ mv -u old.txt new.txt # Does nothing (old is older)
Use case: Updating files only when they're actually newer.
Combining Options
$ mv -iv *.log archive/
mv: overwrite 'archive/error.log'? y
renamed 'error.log' -> 'archive/error.log'
renamed 'access.log' -> 'archive/access.log'
| Option | Purpose | Best Use Case |
|---|---|---|
-i | Interactive - prompt before overwrite | Manual operations on important files |
-v | Verbose - show what's being moved | Debugging, confirming bulk operations |
-n | No clobber - never overwrite | Safe scripts, preventing data loss |
-u | Update - only if newer or doesn't exist | Syncing, updating only changed files |
-f | Force - overwrite without prompt | Automation (default behavior anyway) |
mv vs cp: Key Differences
cp (Copy)
- โ Creates duplicate
- โ Original remains
- โ Requires -r for directories
- โ Only needs read permission on source
- โ Slower (reads and writes data)
- โ Uses disk space (duplicate data)
- โ Works across filesystems freely
mv (Move)
- โ Moves original
- โ Original disappears
- โ No -r needed for directories
- โ Needs write permission on source directory
- โ Instant (just updates metadata, same filesystem)
- โ No extra disk space used
- โ Slower across filesystems (becomes copy+delete)
When mv Becomes Slow
Moving within the same filesystem is instant:
$ mv /home/user/bigfile.iso /home/user/archive/ # Instant
Moving across filesystems requires actual copying:
$ mv /home/user/bigfile.iso /mnt/external/ # Slow (copy + delete)
Why? Different filesystems can't share metadata. Linux must:
- Copy file to destination filesystem
- Delete file from source filesystem
Real-World Use Cases
1. Organizing Downloaded Files
# Move all images to pictures folder
$ mv ~/Downloads/*.jpg ~/Pictures/
$ mv ~/Downloads/*.png ~/Pictures/
# Move PDFs to documents
$ mv ~/Downloads/*.pdf ~/Documents/
# Move archives to dedicated folder
$ mv ~/Downloads/*.{zip,tar.gz,tar.bz2} ~/Archives/
2. Renaming for Clarity
# Rename config backup with date
$ mv nginx.conf nginx.conf.2025-12-15.bak
# Standardize naming convention
$ mv MyDocument.txt my_document.txt
$ mv "file with spaces.txt" file_no_spaces.txt
3. Archiving Log Files
# Create dated archive directory
$ mkdir /var/log/archive/$(date +%Y-%m)
# Move old logs
$ sudo mv /var/log/*.log.1 /var/log/archive/2025-12/
4. Staging Files for Processing
# Move uploaded files to processing queue
$ mv /uploads/incoming/*.csv /processing/queue/
# After processing, move to completed
$ mv /processing/queue/*.csv /processing/completed/
5. Renaming with Patterns
# Add prefix to all files
for file in *.txt; do
mv "$file" "backup_$file"
done
# Remove extension
$ mv report.txt.bak report.txt
Permission Requirements
What You Need for mv
Source permissions:
- Write permission on source directory (to remove entry)
- You don't need write permission on the file itself
Destination permissions:
- Write permission on destination directory (to add entry)
Example: Moving System Files
$ mv /etc/passwd /tmp/
mv: cannot move '/etc/passwd' to '/tmp/passwd': Permission denied
Why it fails: You don't have write permission on /etc (even though /tmp is writable).
Solution: Use sudo if you have privileges:
$ sudo mv /etc/myconfig.conf /etc/myconfig.conf.backup
โ ๏ธ Never move critical system files like /etc/passwd, /etc/shadow, or /boot/vmlinuz unless you absolutely know what you're doing. You can break your system!
Common mv Patterns
Pattern 1: Safe Rename with Backup
# Keep backup of original
$ cp important.conf important.conf.bak
$ mv new-config.conf important.conf
Pattern 2: Bulk Organization
# Move files by type to subdirectories
$ mkdir -p documents/{pdfs,docs,spreadsheets}
$ mv *.pdf documents/pdfs/
$ mv *.doc documents/docs/
$ mv *.{xlsx,xls} documents/spreadsheets/
Pattern 3: Timestamp-Based Moving
# Move files older than 30 days
$ find /tmp -type f -mtime +30 -exec mv {} /archive/ \;
Pattern 4: Interactive Bulk Move
# Prompt for each file (safety for important files)
$ mv -i *.conf /etc/backup/
Pattern 5: Verbose Audit Trail
# Log all moves for audit
$ mv -v /data/*.log /archive/ 2>&1 | tee move-$(date +%F).log
๐งช Practice Labs
๐ฏ Hands-on practice is crucial for mastering mv. These 20 labs progress from basic to advanced real-world scenarios.
Lab 1: Basic Renaming (Beginner)
Task: Create a file called oldname.txt and rename it to newname.txt. Verify the old name no longer exists.
Show Solution
# Create file
touch oldname.txt
# Verify it exists
ls -l oldname.txt
# Rename
mv oldname.txt newname.txt
# Verify rename
ls -l newname.txt # Exists
ls -l oldname.txt # No such file or directory
# Alternative: see both operations
ls -l
# Should show only newname.txt
Key concept: Renaming is just moving to a new name in the same directory.
Lab 2: Moving to Parent Directory (Beginner)
Task: Create /tmp/practice/testfile.txt and move it to /tmp/. Verify it moved correctly.
Show Solution
# Create structure
mkdir -p /tmp/practice
touch /tmp/practice/testfile.txt
# Verify original location
ls -l /tmp/practice/testfile.txt
# Move to parent
cd /tmp/practice
mv testfile.txt ..
# Verify it's gone from practice
ls /tmp/practice/
# Verify it's in parent
ls -l /tmp/testfile.txt
Key concept: .. always refers to the parent directory.
Lab 3: Moving Multiple Files (Beginner)
Task: Create 5 text files in /tmp, then move them all to /tmp/archive/ in one command.
Show Solution
# Create files
cd /tmp
touch file1.txt file2.txt file3.txt file4.txt file5.txt
# Create destination
mkdir archive
# Move all at once
mv file1.txt file2.txt file3.txt file4.txt file5.txt archive/
# Verify
ls /tmp/file*.txt # Should find nothing
ls /tmp/archive/ # Should show all 5 files
# Alternative using wildcard:
touch file{6..10}.txt
mv file*.txt archive/
Key concept: Last argument must be a directory when moving multiple files.
Lab 4: Interactive Mode Safety (Beginner)
Task: Create two files original.txt and backup.txt with different content. Try to overwrite original.txt with backup.txt using -i and decline the overwrite.
Show Solution
# Create files with different content
echo "important data" > original.txt
echo "backup data" > backup.txt
# Verify different content
cat original.txt
cat backup.txt
# Attempt interactive move
mv -i backup.txt original.txt
# When prompted: mv: overwrite 'original.txt'?
# Type: n (no)
# Verify original is unchanged
cat original.txt # Should still show "important data"
ls -l backup.txt # Should still exist
Key concept: -i protects against accidental overwrites.
Lab 5: Moving Directories (Beginner)
Task: Create a directory project with 3 files inside. Move the entire directory to /tmp/projects/.
Show Solution
# Create directory with files
mkdir project
touch project/file{1..3}.txt
# Verify structure
ls -l project/
# Create destination
mkdir -p /tmp/projects
# Move entire directory (no -r needed!)
mv project /tmp/projects/
# Verify move
ls project/ # Should fail (directory moved)
ls /tmp/projects/project/ # Should show 3 files
Key concept: mv doesn't need -r for directories (unlike cp -r).
Lab 6: Verbose Mode (Intermediate)
Task: Create 5 log files and move them to /tmp/logs/ using verbose mode. Observe the output.
Show Solution
# Create files
cd /tmp
touch error.log access.log debug.log system.log app.log
# Create destination
mkdir logs
# Move with verbose output
mv -v *.log logs/
# Expected output:
# renamed 'access.log' -> 'logs/access.log'
# renamed 'app.log' -> 'logs/app.log'
# renamed 'debug.log' -> 'logs/debug.log'
# renamed 'error.log' -> 'logs/error.log'
# renamed 'system.log' -> 'logs/system.log'
# Verify
ls logs/
Key concept: -v shows you exactly what mv didโuseful for audit trails.
Lab 7: No Clobber Mode (Intermediate)
Task: Create file1.txt and file2.txt with different content. Try to move file2.txt to file1.txt using -n. Verify file1.txt remains unchanged.
Show Solution
# Create files with identifiable content
echo "first file" > file1.txt
echo "second file" > file2.txt
# Try to overwrite with -n (no clobber)
mv -n file2.txt file1.txt
# Check contents - file1 should be unchanged
cat file1.txt # Should show "first file"
# file2 should still exist (move didn't happen)
cat file2.txt # Should show "second file"
# Compare to without -n:
echo "first" > test1.txt
echo "second" > test2.txt
mv test2.txt test1.txt # Overwrites silently
cat test1.txt # Shows "second"
ls test2.txt # No such file (was moved/renamed)
Key concept: -n refuses to overwrite, preventing data loss.
Lab 8: Moving with Wildcards (Intermediate)
Task: Create 10 files: 5 with .txt extension and 5 with .log extension. Move only the .txt files to a documents/ folder.
Show Solution
# Create mixed files
touch file{1..5}.txt file{1..5}.log
# Verify mix
ls
# Create destination
mkdir documents
# Move only txt files
mv *.txt documents/
# Verify
ls # Should show only .log files
ls documents/ # Should show only .txt files
# Count to verify
ls *.log | wc -l # Should be 5
ls documents/*.txt | wc -l # Should be 5
Key concept: Wildcards are expanded by the shell before mv sees them.
Lab 9: Renaming with Timestamp (Intermediate)
Task: Create a config file app.conf. Rename it to include today's date in format app.conf.YYYY-MM-DD.
Show Solution
# Create config file
echo "setting=value" > app.conf
# Get today's date
date +%F # Shows YYYY-MM-DD format
# Rename with date
mv app.conf app.conf.$(date +%F)
# Verify
ls -l app.conf.*
# Example result: app.conf.2025-12-15
# Alternative: create backup series
touch nginx.conf
mv nginx.conf nginx.conf.$(date +%F-%H%M%S)
# Result: nginx.conf.2025-12-15-143022
Key concept: Command substitution $(command) lets you embed dates in filenames.
Lab 10: Update Mode Testing (Intermediate)
Task: Create old.txt and wait 5 seconds. Create new.txt. Use mv -u to test update behavior.
Show Solution
# Create old file
echo "old content" > old.txt
# Wait to ensure timestamp difference
sleep 5
# Create newer file
echo "new content" > new.txt
# Check timestamps
ls -l old.txt new.txt
# Test update mode - should overwrite (new is newer)
mv -u new.txt old.txt
# Verify old.txt now has new content
cat old.txt # Should show "new content"
# new.txt was moved
ls new.txt # No such file or directory
# Test opposite direction
echo "old" > file1.txt
sleep 2
echo "new" > file2.txt
cp file2.txt file2-copy.txt
# This does nothing (file1 is older than file2)
mv -u file1.txt file2.txt
ls file1.txt # Still exists (wasn't moved)
Key concept: -u only moves if source is newer or destination doesn't exist.
Lab 11: Moving Across Directories (Intermediate)
Task: Create /tmp/source/file.txt and move it to /tmp/dest/newname.txt (move and rename in one command).
Show Solution
# Create source structure
mkdir -p /tmp/source
echo "test content" > /tmp/source/file.txt
# Create destination directory
mkdir -p /tmp/dest
# Move and rename simultaneously
mv /tmp/source/file.txt /tmp/dest/newname.txt
# Verify
ls /tmp/source/ # Should be empty
ls /tmp/dest/ # Should show newname.txt
cat /tmp/dest/newname.txt # Should show "test content"
Key concept: You can move and rename in a single mv command.
Lab 12: Permission Denied Scenario (Intermediate)
Task: Try to move a file from /tmp to /root/. Understand why it fails and how to fix it.
Show Solution
# Create test file
echo "test" > /tmp/myfile.txt
# Try to move to /root
mv /tmp/myfile.txt /root/
# Expected error: mv: cannot move '/tmp/myfile.txt' to '/root/myfile.txt': Permission denied
# Why? You don't have write permission on /root directory
# Check /root permissions
ls -ld /root
# drwxr-x---. 10 root root 4096 ...
# Only root can write to /root
# Solution: use sudo if you have privileges
sudo mv /tmp/myfile.txt /root/
# Verify
sudo ls /root/myfile.txt
# Alternative: move to your home
mv /tmp/myfile.txt ~/
ls ~/myfile.txt
Key concept: You need write permission on both source and destination directories.
Lab 13: Bulk File Organization (Advanced)
Task: Create 20 files with mixed extensions (.txt, .log, .conf, .sh). Organize them into appropriate subdirectories by type.
Show Solution
# Create mixed files
cd /tmp/organize
touch file{1..5}.txt
touch log{1..5}.log
touch config{1..5}.conf
touch script{1..5}.sh
# Create type-specific directories
mkdir -p {documents,logs,configs,scripts}
# Move by type
mv *.txt documents/
mv *.log logs/
mv *.conf configs/
mv *.sh scripts/
# Verify organization
echo "Documents:"; ls documents/
echo "Logs:"; ls logs/
echo "Configs:"; ls configs/
echo "Scripts:"; ls scripts/
# Verify root is clean
ls /tmp/organize/*.* 2>/dev/null || echo "All files organized!"
Key concept: Wildcards make bulk organization efficient.
Lab 14: Safe Rename with Backup (Advanced)
Task: Rename production.conf to production.conf.old but first create a backup. If something goes wrong, you can restore.
Show Solution
# Create original file
echo "production settings" > production.conf
# Safety: create backup first
cp production.conf production.conf.backup
# Now safely rename
mv production.conf production.conf.old
# Verify
ls production.conf.*
# If you need to restore:
# cp production.conf.backup production.conf
# Better practice: timestamped backups
cp production.conf production.conf.$(date +%F).backup
mv production.conf production.conf.old
Key concept: Always backup critical configs before moving/renaming.
Lab 15: Moving with Character Ranges (Advanced)
Task: Create 26 files named a.txt through z.txt. Move only files from a-m to a first-half/ directory and n-z to second-half/.
Show Solution
# Create alphabet files
touch {a..z}.txt
# Verify all created
ls *.txt | wc -l # Should be 26
# Create destination directories
mkdir first-half second-half
# Move first half (a-m)
mv [a-m].txt first-half/
# Move second half (n-z)
mv [n-z].txt second-half/
# Verify distribution
echo "First half (a-m):"; ls first-half/ | wc -l # Should be 13
echo "Second half (n-z):"; ls second-half/ | wc -l # Should be 13
# Verify root is empty of txt files
ls *.txt 2>/dev/null || echo "All files organized!"
Key concept: Character ranges [a-m] match specific character sets.
Lab 16: Renaming Files in a Loop (Advanced)
Task: Create 5 files named File1.txt through File5.txt (capital F). Rename them all to lowercase file1.txt through file5.txt.
Show Solution
# Create files with capital F
touch File{1..5}.txt
# Verify
ls File*.txt
# Rename to lowercase in loop
for file in File*.txt; do
# Get the new name by converting to lowercase
newname=$(echo "$file" | tr 'F' 'f')
mv "$file" "$newname"
echo "Renamed: $file -> $newname"
done
# Verify all renamed
ls file*.txt # Should show file1.txt through file5.txt
ls File*.txt # Should find nothing
# Alternative using parameter expansion (bash):
for file in File*.txt; do
mv "$file" "${file/File/file}"
done
Key concept: Loops let you apply transformations to multiple filenames.
Lab 17: Moving Files by Age (Advanced)
Task: Create 5 files with different timestamps. Move only files older than 2 minutes to an archive/ directory.
Show Solution
# Create directory
mkdir /tmp/age-test
cd /tmp/age-test
# Create old files (backdated)
touch -t 202512010800 old1.txt
touch -t 202512010900 old2.txt
# Create recent files
touch recent1.txt recent2.txt
# Wait to ensure time difference
sleep 2
# Create destination
mkdir archive
# Find and move files older than 2 minutes
find . -maxdepth 1 -type f -name "*.txt" -mmin +2 -exec mv {} archive/ \;
# Verify
echo "Archived:"; ls archive/
echo "Remaining:"; ls *.txt 2>/dev/null
# Alternative: move files older than 1 day
find . -maxdepth 1 -type f -mtime +1 -exec mv {} archive/ \;
Key concept: Combine find with -exec mv for conditional moves.
Lab 18: Interactive Bulk Move (Advanced)
Task: Create 10 config files. Move them to /etc/backup/ using interactive mode so you can review each one.
Show Solution
# Create test configs in /tmp
cd /tmp
touch config{1..10}.conf
# Create destination (need sudo for /etc)
sudo mkdir -p /etc/backup
# Interactive move (prompts for each file)
sudo mv -i config*.conf /etc/backup/
# For each file, you'll see:
# mv: overwrite '/etc/backup/config1.conf'?
# Type y or n for each
# Verify
sudo ls /etc/backup/
# Alternative: verbose + interactive
sudo mv -iv config*.conf /etc/backup/
# Shows filename AND prompts for overwrite
Key concept: -i with wildcards lets you review each file individually.
Lab 19: Organizing by Date Pattern (Advanced)
Task: Create log files with dates in their names (e.g., app-2025-12-01.log). Move all December logs to a december/ folder and November logs to a november/ folder.
Show Solution
# Create dated log files
cd /tmp/logs
touch app-2025-11-{01..30}.log
touch app-2025-12-{01..15}.log
# Verify
ls -1 | wc -l # Should be 45 files
# Create month directories
mkdir november december
# Move November logs
mv app-2025-11-*.log november/
# Move December logs
mv app-2025-12-*.log december/
# Verify organization
echo "November:"; ls november/ | wc -l # Should be 30
echo "December:"; ls december/ | wc -l # Should be 15
# Alternative: organize by year
mkdir 2025
mv app-2025-*.log 2025/
Key concept: Wildcards can match date patterns for automated log organization.
Lab 20: Complete File Reorganization (Advanced)
Task: You have a messy downloads folder with 50 mixed files. Organize them into proper directories: images/, documents/, archives/, videos/, and other/.
Show Solution
# Create messy downloads directory
mkdir -p ~/Downloads/messy
cd ~/Downloads/messy
# Create mixed files
touch photo{1..10}.jpg
touch video{1..10}.mp4
touch document{1..10}.pdf
touch presentation{1..10}.pptx
touch archive{1..5}.zip
touch archive{6..10}.tar.gz
touch misc{1..5}.txt
# Verify chaos
ls -1 | wc -l # Should be 50 files
# Create organized structure
mkdir -p ~/Downloads/organized/{images,documents,archives,videos,other}
# Move by type
mv *.jpg ~/Downloads/organized/images/
mv *.{mp4,avi,mkv,mov} ~/Downloads/organized/videos/ 2>/dev/null
mv *.{pdf,doc,docx,pptx} ~/Downloads/organized/documents/
mv *.{zip,tar,tar.gz,tar.bz2} ~/Downloads/organized/archives/ 2>/dev/null
mv * ~/Downloads/organized/other/ 2>/dev/null
# Verify organization
cd ~/Downloads/organized
for dir in */; do
echo "$dir: $(ls "$dir" | wc -l) files"
done
# Expected output:
# images/: 10 files
# documents/: 20 files
# archives/: 10 files
# videos/: 10 files
# other/: 5 files (the .txt files)
Key concept: Real-world file organization combines multiple wildcards and organized thinking.
๐ Best Practices
| DO โ | DON'T โ |
|---|---|
Use -i for important files | Move system files carelessly |
Use -v in scripts for audit trails | Assume moves are instant across filesystems |
Test wildcards with ls first | Use wildcards blindly with important data |
| Create backups of critical config files | Move without verifying destination exists |
Use -n in scripts to prevent overwrites | Move files you don't own without sudo |
Verify moves with ls afterward | Forget that mv is permanent (not undo) |
| Use timestamps in renamed backups | Move to nonexistent destination directories |
| Quote filenames with spaces | Use mv in aliases that could cause confusion |
The Safe mv Workflow
# 1. Test your wildcard pattern
ls *.log
# 2. Verify destination exists
ls -ld /archive/
# 3. Use verbose + interactive for safety
mv -iv *.log /archive/
# 4. Verify the move
ls *.log # Should find nothing
ls /archive/ # Should show your files
๐จ Common Pitfalls to Avoid
Pitfall 1: Accidentally Overwriting Files
# DANGEROUS
mv important.txt backup.txt
# If backup.txt exists, it's silently overwritten!
# SAFE
mv -i important.txt backup.txt
# Prompts before overwriting
# SAFEST
mv -n important.txt backup.txt
# Never overwrites
Pitfall 2: Moving to Nonexistent Directory
# FAILS
mv file.txt /nonexistent/directory/
# mv: cannot move 'file.txt' to '/nonexistent/directory/': No such file or directory
# CORRECT
mkdir -p /nonexistent/directory/
mv file.txt /nonexistent/directory/
Pitfall 3: Assuming mv is Instant Everywhere
# INSTANT (same filesystem)
mv /home/user/bigfile /home/user/archive/
# SLOW (different filesystem - becomes copy+delete)
mv /home/user/bigfile /mnt/external/
Pitfall 4: Moving System Files
# BREAKS YOUR SYSTEM
sudo mv /bin/bash /tmp/
# Now bash is gone! You can't run shell scripts!
# Never move:
# - /bin, /sbin, /usr/bin executables
# - /etc/passwd, /etc/shadow
# - /boot files
# - Any file you're not 100% sure about
Pitfall 5: Wildcards Matching More Than Expected
# Intended: move .txt files
mv *.txt archive/
# Problem: also matches .txt.bak, .txt.old
ls *.txt
# file.txt file.txt.bak file.txt.old <- all moved!
# Solution: be more specific
mv *.txt archive/
mv *.txt.bak backups/
Pitfall 6: Not Quoting Filenames with Spaces
# WRONG
mv my file.txt documents/
# mv interprets as: mv "my" "file.txt" "documents/"
# Error: target 'documents/' is not a directory
# CORRECT
mv "my file.txt" documents/
# or
mv 'my file.txt' documents/
Pitfall 7: Permission Confusion
# Can read but can't move
ls -l /etc/passwd # Can read
mv /etc/passwd /tmp/ # Can't move (need write on /etc)
# Why? mv needs:
# - Write permission on SOURCE directory (/etc)
# - Write permission on DESTINATION directory (/tmp)
๐ Command Cheat Sheet
Basic Operations
# Rename file in same directory
mv oldname.txt newname.txt
# Move file to directory
mv file.txt /destination/
# Move and rename
mv file.txt /destination/newname.txt
# Move multiple files
mv file1 file2 file3 /destination/
# Move directory (no -r needed)
mv mydir/ /destination/
With Options
# Interactive (prompt before overwrite)
mv -i file.txt /destination/
# Verbose (show what's happening)
mv -v file.txt /destination/
# No clobber (never overwrite)
mv -n file.txt /destination/
# Update (only if newer or doesn't exist)
mv -u file.txt /destination/
# Combined options
mv -iv *.log /archive/
Real-World Patterns
# Rename with timestamp
mv config.conf config.conf.$(date +%F)
# Move by file type
mv *.txt documents/
mv *.log logs/
# Move files older than 30 days
find /tmp -mtime +30 -exec mv {} /archive/ \;
# Bulk organization
mkdir -p {docs,images,videos}
mv *.pdf docs/
mv *.jpg images/
mv *.mp4 videos/
# Safe config file rename
cp nginx.conf nginx.conf.backup
mv nginx.conf nginx.conf.old
# Move with wildcard patterns
mv [abc]*.txt group1/
mv [0-9]*.log dated-logs/
Troubleshooting
# Check permissions
ls -ld /source-dir /dest-dir
# Test wildcard before moving
ls *.txt # See what would move
# Verify after moving
ls /destination/
# Undo a move (if realized immediately)
mv /destination/file.txt .
๐ฏ Key Takeaways
Master These Concepts:
- mv moves, doesn't copy - Original disappears
- Renaming is moving - Same command, just different destination
- No -r for directories - mv handles them naturally
- Instant on same filesystem - Only updates metadata
- Slow across filesystems - Must copy then delete
- Use -i for safety - Interactive mode prevents mistakes
- Use -n in scripts - Never overwrite, no prompts
- Test wildcards first - Use ls to preview what matches
- Permission requirements - Write on both source and destination directories
- No undo - mv is permanent, backups are essential
Quick Decision Guide
Need to keep original?
โโ Yes โ Use cp
โโ No โ Use mv
Moving important files?
โโ Use mv -i (interactive)
Moving in script?
โโ Use mv -n (no clobber) or mv -u (update)
Need audit trail?
โโ Use mv -v (verbose)
Moving directories?
โโ Just mv dirname/ dest/ (no -r needed)
Cross-filesystem move?
โโ Expect slower operation (copy + delete)
๐ What's Next?
Now that you've mastered moving and renaming files, you're ready to explore more powerful file management operations!
Coming Up Next:
- Post 26: Removing Files and Directories with rm and rmdir
- Post 27: Understanding Hard Links and Symbolic Links
- Post 28: Finding Files with find and locate
- Post 29: Text File Viewing with cat, less, more, head, and tail
๐ Congratulations! You now understand how to move and rename files efficiently with mv. You've learned:
- The dual nature of mv (moving AND renaming)
- Essential flags for safe operations (-i, -v, -n, -u)
- How mv differs from cp
- Real-world file organization workflows
- Permission requirements
- Common pitfalls and how to avoid them
The mv command is your tool for reorganizing files, renaming for clarity, and keeping your filesystem organized. Combined with cp and mkdir, you now have complete control over file and directory management!
Practice these labs until mv operations become second natureโyou'll use this command constantly as a Linux administrator! ๐

