Sometimes, you may need to move files from one directory location to another in Linux. This can be achieved using the mv command.
The Basic Syntax for moving files using the mv command
The basic syntax for using the mv command to move files is to type mv space name of the target file you want to move, space and the destination where you want the file to be moved to. This is seen below:
mv Target_filename Target_destination
The Target_filename represents the file or directory that you want to move and the Target_destination is the directory path or location where you want the file to be moved to.
Moving a single file using the mv command
Let’s say there is a file named Items.txt in your current directory, and you want to move it to a folder named Documents, you can type the following on your terminal:
mv Items.txt Documents/
The above command will move Items.txt to the Documents folder.
To confirm if the file has been moved to the target destination, you can type ls followed by the name of the destination directory, which in this case is Documents.
ls Documents
You’ll see that Items.txt is present in the Documents folder.
Moving Multiple Files using the mv command
The mv command also allows you to move multiple files at once by typing all the names of the target files you want to move.
For example, if you want to move two files, let’s say file1.txt and file2.txt, to the Documents folder, on your terminal, here is the command you will run:
mv file1.txt file2.txt Documents/
The above command will move both files to the Documents directory.
Moving Directories using the mv command
If you want to move an entire folder, the process is the same. For example, to move a folder named Projects into the Documents folder, type the following command:
mv Projects Documents/
The entire Projects folder will be relocated to the Documents directory.
Now, you will notice that while moving directories, we don’t use the -r option as this is not required. The mv command handles directories by default without needing a recursive flag. The -r (or –recursive) option is necessary for commands like cp when copying directories, but for moving directories, it’s not needed.