How to use the Linux mv command to move files and directories
With the Linux mv command you can move files or even entire directories. You can even use the command to rename them, however, other commands are better suited for this purpose.
What is the Linux mv command?
This Linux mv command has two important functions. The first is to move files from one directory to another. You can also use the command to move whole directories. The second allows you to rename files or folders. However, other Linux commands and graphic interfaces are usually better suited for this task. The mv command works in all common Linux distributions such as Ubuntu. Its name is derived from the word ‘move’.
How does the mv command work?
When using the mv command, users request that the system moves a specific file or a complete directory from one place to another. There are two different ways to do this: You can either first open the source directory with the Linux cd command and move the file from there to the target directory or you can set the source directory in the command and carry out the move from another working directory. We will show you examples of both at the end of this guide. To rename a file, you simply put the new name where you normally put the target directory.
What does the mv syntax look like?
The syntax for Linux mv looks as follows:
$ mv [Option] [Source] [Target]
shellmv is the actual command which can be adjusted using the options. [Source] and [Target] can be both files or directories. However, it’s important that the source is stipulated before the target. On top of this, you also need to ensure that there are no typos otherwise the command won’t work.
What options does the mv command have?
You have three options in mv:
- -i or –interactive: This option will tell the system to ask whether a file or directory should be overwritten.
- -u or –update: This option will only move a source if the target file is older.
- -v or –verbose: This option will show the progress of any move.
Examples of a mv command
To better understand exactly how Linux mv works, here are a few examples:
$ mv customers.txt ~/Documents/Contacts/
shellThis command moves the file customers.txt from its current directory to the new directory ~/Documents/Contacts/.
$ mv /Home/Invoices/customers.txt /Documents/Contacts/
shellYou can use this option to move the file customers.txt from the folder /home/invoices to the new one /Documents/Contacts/.
mv *.txt /Documents/
shellThis moves all files with a .txt extension to the folder /Documents/.
$ mv customers.txt customers_new.txt
shellThis renames the file from customers.txt to customers_new.txt.
$ mv Invoices Invoices_old
shellThis renames the folder /Invoices/ in the current directory to /Invoices_old/.