Linux mv Command

In the realm of Linux command-line utilities, the mv command stands out as a powerful tool for moving and renaming files and directories. The name mv is short for "move," but it also serves the purpose of renaming files or directories. In this blog post, we'll explore the various facets of the mv command, its diverse usage, options, and practical examples to help you master file and directory manipulation in Linux.

Basic Usage

The basic syntax of the mv command is quite straightforward:

bash
mv <source> <destination>

Here's how you can use it to move a file:

bash
mv file.txt /path/to/destination/

Or to rename a file:

bash
mv old_file.txt new_file.txt

To move a directory and its contents:

bash
mv directory/ /path/to/destination/

Common Options

The mv command supports several options to tailor its behavior according to your requirements:

  • -i or --interactive: Prompts before overwriting any existing files.
bash
mv -i file.txt /path/to/destination/
  • -u or --update: Moves files only if the source is newer than the destination or if the destination is missing.
bash
mv -u file.txt /path/to/destination/
  • -v or --verbose: Provides verbose output, showing the files being moved.
bash
mv -v file.txt /path/to/destination/

Moving and Renaming Files

The mv command is primarily used to move files or directories, but it can also be used to rename files. By specifying a new name as the destination, you effectively rename the file.

bash
mv old_file.txt new_file.txt

Overwriting Files

By default, mv will overwrite the destination file if it already exists. To avoid overwriting, you can use the -i option to prompt for confirmation before overwriting.

bash
mv -i file.txt /path/to/destination/

Practical Examples

  1. Moving Files:

    bash
    mv file.txt /path/to/destination/
  2. Renaming Files:

    bash
    mv old_file.txt new_file.txt
  3. Moving Files Verbosely:

    bash
    mv -v file.txt /path/to/destination/
  4. Prompting before Overwriting:

    bash
    mv -i file.txt /path/to/destination/