mv - Linux


Overview

The mv command in Linux is used for moving or renaming files and directories. Its primary function is to relocate contents from one place to another or change a file’s name. It is an essential utility for managing file systems, performing organized backups, restructuring folders, or simply renaming items.

Syntax

The basic syntax for the mv command is:

mv [OPTIONS] source destination
  • source: The file or directory to be moved or renamed.
  • destination: The new location or name for the source.

Multiple files can be moved at once by providing multiple sources before the destination, which must be a directory:

mv [OPTIONS] source1 source2 source3 ... destination_directory

Options/Flags

  • -i, --interactive: Prompt before overwrite. This option asks for confirmation before moving a file that would overwrite an existing file at the destination.
  • -u, --update: Moves only when the source is newer than the destination or when the destination is missing.
  • -v, --verbose: Provides a detailed description of the move operation, showing what is being moved where.
  • -n, --no-clobber: Prevents an existing file from being overwritten.
  • -t, --target-directory=DIRECTORY: Move all sources into a DIRECTORY.
  • --help: Displays help information about the mv command.
  • --version: Outputs version information of the mv tool.

Examples

  1. Rename a File:

    mv old_filename.txt new_filename.txt
    
  2. Move multiple files to a directory:

    mv file1.txt file2.txt /path/to/directory/
    
  3. Move files interactively to prevent accidental overwrites:

    mv -i source.txt target.txt
    
  4. Update moved files only if they are newer:

    mv -u old_report.txt /archive/reports/
    
  5. Use verbose to track what is being moved:

    mv -v documents/ /backup/documents/
    

Common Issues

  • Overwriting Files: Without flags, mv can inadvertently overwrite destination files. Using -i or -n can prevent this.
  • Moving Hidden Files: Users sometimes forget that hidden files (starting with a dot) aren’t moved using a wildcard (*). Use the pattern .* to include hidden files.

Integration

mv can be paired with other commands for powerful scripts or command chains. Here’s an example using find:

find /path/to/source -name '*.tmp' -exec mv {} /path/to/destination \;

This command finds all .tmp files within a directory and moves them to a new location.

  • cp: Copies files or directories.
  • rm: Removes files or directories.
  • rename: Renames files based on patterns.

Further reading and detailed options for the mv command can be found in its man page:

man mv

By understanding and utilizing the various options provided by the mv command, users can efficiently manage file and directory organization within their systems.