Complete mv Command Guide: Move & Rename Files in Linux

Master the Linux mv command with this comprehensive guide covering file moving, renaming, directory operations, and advanced usage with practical examples.

The mv Command: Complete Guide to Moving and Renaming Files in Linux

Table of Contents

1. [Introduction](#introduction) 2. [Basic Syntax](#basic-syntax) 3. [Command Options](#command-options) 4. [Moving Files](#moving-files) 5. [Renaming Files](#renaming-files) 6. [Moving Directories](#moving-directories) 7. [Advanced Usage](#advanced-usage) 8. [Common Use Cases](#common-use-cases) 9. [Error Handling](#error-handling) 10. [Best Practices](#best-practices) 11. [Examples and Scenarios](#examples-and-scenarios) 12. [Troubleshooting](#troubleshooting)

Introduction

The mv command is one of the most fundamental and frequently used commands in Unix and Linux systems. It serves dual purposes: moving files and directories from one location to another, and renaming files and directories. Unlike the cp command which creates copies, mv actually relocates the original file or directory, making it an efficient operation that doesn't consume additional disk space.

The mv command works by updating directory entries rather than copying data blocks, which makes it extremely fast regardless of file size when moving within the same filesystem. When moving across different filesystems, the operation becomes equivalent to copying and then deleting the original.

Basic Syntax

The fundamental syntax of the mv command follows this pattern:

`bash mv [OPTIONS] SOURCE DESTINATION `

Where: - SOURCE is the file or directory you want to move or rename - DESTINATION is the target location or new name - OPTIONS are various flags that modify the command's behavior

Multiple Sources Syntax

When moving multiple files to a directory:

`bash mv [OPTIONS] SOURCE1 SOURCE2 ... DESTINATION_DIRECTORY `

Command Options

The mv command supports several options that modify its behavior. Here's a comprehensive table of available options:

| Option | Long Form | Description | Example | |--------|-----------|-------------|---------| | -i | --interactive | Prompt before overwriting existing files | mv -i file1.txt file2.txt | | -f | --force | Force move without prompting, override -i | mv -f file1.txt file2.txt | | -n | --no-clobber | Never overwrite existing files | mv -n file1.txt file2.txt | | -u | --update | Move only if source is newer or destination missing | mv -u file1.txt file2.txt | | -v | --verbose | Display detailed information about operations | mv -v file1.txt file2.txt | | -b | --backup | Create backup of destination files before overwriting | mv -b file1.txt file2.txt | | -S | --suffix=SUFFIX | Override backup suffix (default is ~) | mv -b -S .bak file1.txt file2.txt | | -t | --target-directory=DIR | Specify target directory | mv -t /home/user/ file1.txt file2.txt | | -T | --no-target-directory | Treat destination as normal file | mv -T source dest | | --help | | Display help information | mv --help | | --version | | Display version information | mv --version |

Option Combinations

Options can be combined for more sophisticated operations:

`bash mv -iv file1.txt file2.txt # Interactive and verbose mv -bv file1.txt file2.txt # Backup and verbose mv -fuv file1.txt file2.txt # Force, update, and verbose `

Moving Files

Basic File Moving

Moving a file from one location to another is the primary function of the mv command:

`bash

Move file to different directory

mv document.txt /home/user/documents/

Move file to different directory with new name

mv document.txt /home/user/documents/important_document.txt

Move file to parent directory

mv document.txt ../

Move file to current directory from subdirectory

mv subdirectory/document.txt . `

Moving Multiple Files

When moving multiple files, the destination must be a directory:

`bash

Move multiple files to a directory

mv file1.txt file2.txt file3.txt /destination/directory/

Using wildcards to move multiple files

mv *.txt /destination/directory/ mv file*.log /var/log/ mv image*.jpg /home/user/pictures/ `

Moving Files with Patterns

The mv command works seamlessly with shell wildcards and patterns:

| Pattern | Description | Example | |---------|-------------|---------| | | Matches any characters | mv .txt /docs/ | | ? | Matches single character | mv file?.txt /docs/ | | [abc] | Matches any character in brackets | mv file[123].txt /docs/ | | [a-z] | Matches any character in range | mv file[a-z].txt /docs/ | | {pattern1,pattern2} | Matches either pattern | mv file{1,2,3}.txt /docs/ |

Renaming Files

Renaming is accomplished by specifying a new name as the destination while keeping the file in the same directory:

Basic Renaming

`bash

Rename a file in the same directory

mv oldname.txt newname.txt

Rename with path specification

mv /path/to/oldname.txt /path/to/newname.txt

Rename and move simultaneously

mv /old/path/oldname.txt /new/path/newname.txt `

Renaming with Special Characters

When dealing with files containing spaces or special characters, use quotes:

`bash

Files with spaces

mv "old file name.txt" "new file name.txt" mv 'file with spaces.txt' 'renamed file.txt'

Files with special characters

mv "file\$pecial.txt" "normal_file.txt" mv "file(1).txt" "file_1.txt" `

Batch Renaming Techniques

For batch renaming operations, combine mv with other commands:

`bash

Using a loop for batch renaming

for file in *.txt; do mv "$file" "backup_$file" done

Rename with date prefix

for file in *.log; do mv "$file" "$(date +%Y%m%d)_$file" done

Remove spaces from filenames

for file in \ ; do mv "$file" "${file// /_}" done `

Moving Directories

Basic Directory Moving

Moving directories works similarly to moving files:

`bash

Move directory to another location

mv /source/directory /destination/

Move and rename directory

mv old_directory new_directory

Move directory into another directory

mv project_folder /home/user/projects/ `

Moving Directory Contents

To move all contents of a directory without moving the directory itself:

`bash

Move all files from source to destination

mv /source/directory/* /destination/directory/

Move all files including hidden files

mv /source/directory/{,.[^.]} /destination/directory/

Using find command for more control

find /source/directory -maxdepth 1 -type f -exec mv {} /destination/directory/ \; `

Directory Moving Scenarios

| Scenario | Command | Result | |----------|---------|---------| | Move dir to existing dir | mv dir1 existing_dir/ | dir1 becomes existing_dir/dir1 | | Move dir to non-existing path | mv dir1 new_name | dir1 is renamed to new_name | | Move multiple dirs | mv dir1 dir2 dir3 target_dir/ | All dirs moved into target_dir |

Advanced Usage

Using mv with Find

Combine mv with find for powerful file management:

`bash

Move all files older than 30 days

find /source -type f -mtime +30 -exec mv {} /archive/ \;

Move files by size

find /source -type f -size +100M -exec mv {} /large_files/ \;

Move files by extension with confirmation

find /source -name "*.log" -exec mv -i {} /logs/ \; `

Using mv with xargs

For handling large numbers of files efficiently:

`bash

Move many files using xargs

find /source -name "*.tmp" | xargs -I {} mv {} /temp/

Move files with null delimiter (handles spaces better)

find /source -name "*.bak" -print0 | xargs -0 -I {} mv {} /backup/ `

Conditional Moving

Move files based on conditions:

`bash

Move only if destination doesn't exist

[ ! -f /destination/file.txt ] && mv /source/file.txt /destination/

Move with timestamp check

if [ /source/file.txt -nt /destination/file.txt ]; then mv /source/file.txt /destination/ fi `

Common Use Cases

File Organization

`bash

Organize downloads by file type

mv ~/Downloads/*.pdf ~/Documents/PDFs/ mv ~/Downloads/*.jpg ~/Pictures/ mv ~/Downloads/*.mp3 ~/Music/

Sort files by creation date

mkdir -p ~/Archive/$(date +%Y/%m) mv ~/Downloads/* ~/Archive/$(date +%Y/%m)/ `

Log Management

`bash

Archive old log files

mv /var/log/application.log /var/log/archive/application_$(date +%Y%m%d).log

Rotate log files

mv /var/log/app.log.3 /var/log/app.log.4 mv /var/log/app.log.2 /var/log/app.log.3 mv /var/log/app.log.1 /var/log/app.log.2 mv /var/log/app.log /var/log/app.log.1 `

Backup Operations

`bash

Create backup before updating

mv config.conf config.conf.backup mv new_config.conf config.conf

Timestamped backups

mv database.sql database_$(date +%Y%m%d_%H%M%S).sql.backup `

Development Workflows

`bash

Version control operations

mv feature_branch_code.py main_code.py

Deployment preparations

mv /development/app /production/app_old mv /staging/app /production/app `

Error Handling

Common Error Messages

| Error Message | Cause | Solution | |---------------|-------|----------| | Permission denied | Insufficient permissions | Use sudo or check file permissions | | No such file or directory | Source doesn't exist | Verify source path | | Directory not empty | Target directory exists and not empty | Use -f or clear target directory | | Operation not permitted | System protection or immutable files | Check file attributes with lsattr | | Device or resource busy | File is in use | Close applications using the file |

Error Prevention Strategies

`bash

Check if source exists before moving

if [ -f "source_file.txt" ]; then mv source_file.txt destination/ else echo "Source file does not exist" fi

Verify destination directory exists

mkdir -p /destination/directory mv file.txt /destination/directory/

Use test mode with echo

echo mv source.txt destination.txt # Preview command `

Handling Special Cases

`bash

Moving files with special permissions

sudo mv /system/file /backup/ chmod --reference=/backup/original_file /backup/file

Moving across filesystems

rsync -av /source/file /destination/ && rm /source/file

Handling symbolic links

mv -L symbolic_link /destination/ # Follow link mv symbolic_link /destination/ # Move link itself `

Best Practices

Safety Measures

1. Always use absolute paths for critical operations: `bash mv /full/path/to/source /full/path/to/destination `

2. Use interactive mode for important files: `bash mv -i important_file.txt /destination/ `

3. Create backups before overwriting: `bash mv -b original_file.txt /destination/ `

4. Test with echo for complex operations: `bash echo mv complex_pattern* /destination/ `

Performance Considerations

| Scenario | Performance Impact | Recommendation | |----------|-------------------|----------------| | Same filesystem | Very fast (metadata update) | Preferred method | | Different filesystem | Slower (copy + delete) | Consider rsync for large files | | Network filesystems | Variable speed | Monitor progress with -v | | Many small files | Can be slow | Consider archiving first |

Scripting Best Practices

`bash #!/bin/bash

Safe mv script template

set -euo pipefail # Exit on error, undefined vars, pipe failures

source_file="$1" dest_file="$2"

Validate inputs

if [ $# -ne 2 ]; then echo "Usage: $0 source destination" exit 1 fi

Check source exists

if [ ! -e "$source_file" ]; then echo "Error: Source file '$source_file' does not exist" exit 1 fi

Confirm operation

echo "Moving '$source_file' to '$dest_file'" read -p "Continue? (y/N): " confirm if [[ $confirm =~ ^[Yy]$ ]]; then mv "$source_file" "$dest_file" echo "Move completed successfully" else echo "Operation cancelled" fi `

Examples and Scenarios

Scenario 1: Project File Reorganization

`bash

Initial structure

project/ ├── main.py ├── utils.py ├── config.txt ├── data.csv └── output.log

Reorganize into subdirectories

mkdir -p project/{src,config,data,logs} mv project/main.py project/utils.py project/src/ mv project/config.txt project/config/ mv project/data.csv project/data/ mv project/output.log project/logs/ `

Scenario 2: Batch Photo Organization

`bash

Organize photos by date taken (requires exiftool)

for photo in *.jpg; do date=$(exiftool -d "%Y/%m" -DateTimeOriginal -S -s "$photo") mkdir -p "Photos/$date" mv "$photo" "Photos/$date/" done `

Scenario 3: Log Rotation System

`bash #!/bin/bash

Simple log rotation script

log_file="/var/log/application.log" max_logs=5

Rotate existing logs

for ((i=max_logs; i>1; i--)); do if [ -f "${log_file}.$((i-1))" ]; then mv "${log_file}.$((i-1))" "${log_file}.$i" fi done

Move current log to .1

if [ -f "$log_file" ]; then mv "$log_file" "${log_file}.1" fi

Create new log file

touch "$log_file" `

Scenario 4: Cleanup and Archiving

`bash

Archive old files (older than 90 days)

archive_dir="/archive/$(date +%Y/%m)" mkdir -p "$archive_dir"

find /data -type f -mtime +90 -print0 | while IFS= read -r -d '' file; do echo "Archiving: $file" mv "$file" "$archive_dir/" done `

Troubleshooting

Permission Issues

`bash

Check file permissions

ls -la source_file.txt

Check directory permissions

ls -ld /destination/directory/

Fix permissions if necessary

chmod 644 source_file.txt chmod 755 /destination/directory/ `

Cross-Filesystem Moves

When moving across different filesystems, mv performs a copy and delete operation:

`bash

Monitor cross-filesystem moves

mv -v large_file.dat /different/filesystem/

Alternative for large files

rsync -av --progress large_file.dat /different/filesystem/ && rm large_file.dat `

Handling Locked Files

`bash

Check which processes are using a file

lsof filename.txt

Find processes by file

fuser filename.txt

Force move after stopping processes

sudo systemctl stop application mv locked_file.txt /destination/ sudo systemctl start application `

Recovery from Failed Moves

`bash

Check system logs for errors

journalctl | grep mv

Verify filesystem integrity

fsck /dev/sdX

Check disk space

df -h

Monitor system resources during moves

iostat -x 1 `

The mv command is an essential tool for file system management in Linux and Unix systems. Its dual functionality of moving and renaming files makes it indispensable for system administration, file organization, and automation scripts. Understanding its various options and use cases enables efficient file management and helps prevent data loss through proper usage patterns and safety measures.

Tags

  • Command Line
  • Linux
  • Unix
  • file management
  • system-administration

Related Articles

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

Complete mv Command Guide: Move & Rename Files in Linux