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.txtThe exact same syntax applies to directories:
mv old_directory_name new_directory_nameSafely 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:
- Preventing accidental overwrites (
-n): The--no-clobberoption prevents an existing file from being overwritten.mv -n source.txt existing_file.txt - Interactive prompting (
-i): Forcesmvto ask for user confirmation before overwriting an existing destination file.mv -i source.txt existing_file.txt
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.txtYou can also customize the backup suffix using the -S
flag:
mv -b -S .bak source.txt target.txtConditional 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.txtBatch 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