How to Use mv Command in Linux: Syntax, Examples, and Tips
The
mv command in Linux moves or renames files and directories by specifying the source and destination paths. Use mv source target to move or rename, where source is the file or directory to move and target is the new location or name.Syntax
The basic syntax of the mv command is:
mv [options] source targetsource: The file or directory you want to move or rename.target: The destination path or new name.options: Optional flags to modify behavior, like-ifor interactive mode.
bash
mv [options] source target
Example
This example moves a file named report.txt from the current directory to a folder named backup. It also renames oldname.txt to newname.txt in the current directory.
bash
mkdir -p backup mv report.txt backup/ mv oldname.txt newname.txt
Common Pitfalls
Common mistakes include accidentally overwriting files without warning and moving files to wrong locations. Use the -i option to ask before overwriting. Also, ensure the target directory exists to avoid errors.
bash
mv report.txt backup/
# If backup/report.txt exists, it will be overwritten silently
mv -i report.txt backup/
# Prompts before overwriting if backup/report.txt existsQuick Reference
| Option | Description |
|---|---|
| -i | Ask before overwriting files |
| -f | Force move without prompt (default) |
| -n | Do not overwrite existing files |
| -v | Show details of the move operation |
Key Takeaways
Use
mv source target to move or rename files and directories.Add
-i option to avoid accidental overwrites by prompting before replacing files.Ensure the target directory exists before moving files to avoid errors.
Use
-v option to see what the command is doing.Without options,
mv overwrites files silently if the target exists.