Moving files and directories is one of the basic tasks that you often need to perform on a Linux system. In this tutorial, we will explain how to use the mv command to move files and directories.
How to use the mv command
mv command (move short) for file and directory rename, and move from one location to another. Mv command syntax is as follows:
mv [OPTIONS] source destination
Source may be one or more files or directories, the target may be a single file or directory.
- If you specify more than one file or directory as the source, the destination must be a directory. In this case, the source files will be moved to the target directory.
- If a single file as the source, the target and the target is an existing directory, the files are moved to the specified directory.
- If you specify a single file as the source, specify a single file as the target goal, you will rename the file.
- If the source is a directory rather than the goal, the goal will be renamed to the source, or it will be moved to the target directory.
- To move a file or directory, you need to have write access to the source and destination. Otherwise, you will receive a permission denied error.
Command to move the directory with the same command when moving files. In the following example, if dir2 directory exists, the command will move dir2 in dir1. If dir2 does not exist, dir1 will be renamed to dir2:
etc. dir1 dir2
Move multiple files and directories
mv command options
type mv
If an alias is mv, the output would be as follows:
mv is aliased to `mv -i'
If the conflict option is specified, the option specified last takes precedence.
Prompt before covering
By default, if the target file exists, it will be overwritten. To confirm the prompt, use the -i option:
prompt
To overwrite the file type, enter the character y or Y.
Mandatory coverage
If you try to overwrite read-only files, mv command will ask whether you want to overwrite the file:
prompt
To avoid being prompted, use the -f option:
When you need to cover multiple files read-only mode, this option is particularly useful.
Do not overwrite existing files
-n option tells mv never overwrite any existing files:
As shown below:
backup file
If the target file exists, it can create backup -b option:
Backup file having the same name as the original document, and appends a tilde (~).
Use the ls command to verify that the backup has been created:
Verbose output
Another useful option is -v. When you use this option, the command will print the name of each file movement:
Output:
to sum up
By now, you should have a good understanding of how to use the mv command to move files and directories. New Linux users threatened by the command line can use the GUI file manager to move files.
For more information on the mv command, see the man page.
If you have any questions or feedback, please feel free to comment.