Linux mv Command Uses Beyond Moving Files

While the Linux mv command is primarily known for relocating files and directories between paths, its most common secondary function is renaming them. Because the Linux filesystem treats renaming as moving an item to a new name within the same directory, mv serves as the standard, built-in renaming utility. Beyond renaming, the command is also widely utilized for safely overwriting files, managing automated file backups during replacement, updating destination files based on modification timestamps, and executing bulk renaming operations via shell scripts.

Renaming Files and Directories

Linux does not feature a standalone, dedicated rename command by default in all distributions, making mv the primary utility for changing names. When the source and destination paths reside in the same directory, mv simply re-links the file or directory metadata to the new name without transferring data blocks on the storage device.

To rename a single file:

mv old_filename.txt new_filename.txt

The exact same syntax applies to directories:

mv old_directory_name new_directory_name

Safely Replacing Existing Target Files

When moving or renaming a file to a destination name that already exists, mv will overwrite the target by default. However, specific flags modify this behavior to manage how targets are replaced:

Automatic Backups During Replacement

The mv command can automatically generate backups of existing files before replacing them. By using the -b flag, the destination file is renamed with a tilde suffix (~) before the source file takes its place.

mv -b source.txt target.txt

You can also customize the backup suffix using the -S flag:

mv -b -S .bak source.txt target.txt

Conditional Updates (-u)

The mv command functions as an update tool using the -u (or --update) option. When this flag is passed, the command only overwrites the target file if the source file is newer than the target, or if the target file does not yet exist.

mv -u source.txt target.txt

Batch Renaming with Shell Loops

Administrators frequently pair mv with Bash shell loops to perform batch renaming tasks, such as changing file extensions or adding prefixes.

To change all .jpeg extensions to .jpg in the current directory:

for file in *.jpeg; do
    mv "$file" "${file%.jpeg}.jpg"
done