Mv Command - Move Files & Directories | Online Free DevTools by Hexmos

Learn how to use the mv command to move files and directories in Linux/Unix. Explore options like -f, -i, -n, and -t for efficient file management.

Mv Command

The mv command is a fundamental utility in Unix-like operating systems used for moving or renaming files and directories. It's a versatile tool that allows for efficient file management directly from the command line.

Basic File Movement

The most common use of mv is to move a file from its current location to a new directory. If the destination is a file that already exists, it will be overwritten by default.

# To move a file from one place to another:
mv <src> <dest>

Overwriting Files

mv provides options to control its behavior when encountering existing files at the destination.

Force Overwrite

The -f option forces the move operation, overwriting the destination file without prompting for confirmation. This is useful in scripts where user interaction is not desired.

# To move a file from one place to another and automatically overwrite if the destination file exists:
# (This will override any previous -i or -n args)
mv -f <src> <dest>

Interactive Overwrite

Using the -i option prompts the user before overwriting an existing file. This is a safer approach for manual operations to prevent accidental data loss.

# To move a file from one place to another but ask before overwriting an existing file:
# (This will override any previous -f or -n args)
mv -i <src> <dest>

No Overwrite

The -n option prevents overwriting any existing file at the destination. If a file with the same name exists, the move operation for that specific file will be skipped.

# To move a file from one place to another but never overwrite anything:
# (This will override any previous -f or -i args)
mv -n <src> <dest>

Moving Multiple Files to a Directory

The -t option allows you to specify the target directory first, followed by the list of files to be moved into it. This is particularly handy when moving many files.

# To move listed file(s) to a directory
mv -t <dest> <file>...

Renaming Files and Directories

When the source and destination are in the same directory, mv effectively renames the file or directory. If the destination is a directory, the source is moved into it. If the destination is a new name, the source is renamed to that name.

Further Resources