LAST UPDATED: JULY 16, 2021
How to Move a File or Directory in Linux
In Linux, if we want to move a file or directory, we can use the mv
command. For example,
$ mv myfile.txt /destination/folder
The mv
(move) command is used to move one or more files or directories.
The mv
command is also used to rename files or directories and the major advantage of the mv
command is that no additional space is consumed on a disk during renaming.
The general syntax of the mv command
mv [OPTION]... SOURCE... DIRECTORY
Linux mv command Options
The following table contains a brief description of options available with the mv command.
Options |
Description |
--backup[=CONTROL] |
It is used to make a backup of each existing destination file. |
-b |
It is similar to --backup but does not accept an argument. |
-f, --force |
It does not prompt before overwriting. It moves forcefully. |
-n, --no-clobber |
do not overwrite an existing file |
--strip-trailing-slashes |
It is used to remove any trailing slashes from each SOURCE argument. |
-S, --suffix=SUFFIX |
It overrides the usual backup suffix. |
-t, --target-directory |
It moves all SOURCE arguments into DIRECTORY. |
-T, --no-target-directory=DIRECTORY |
It treats DEST as a normal file. |
-u, --update |
It moves only when the SOURCE file is newer than the destination file. |
-v, --verbose |
It is used to explain what is being done. |
-Z, --context |
It is used to set the SELinux security context of the destination file to default type. |
--help |
It displays help. |
Move a file from one directory to another directory
In this example, snow.sh file is available in shadow directory, and by using mv command snow.sh file moved to the destination directory.
Rename a file using mv command
Here the file hello.cnf after using mv command is rename to dubey.cnf file which not existed already. If the destination file already exists, then it will be overwritten and the source file will be deleted automatically without any prompt.
Take a backup of the existing file
In this example, using -b (backup) option with mv command it is easier to take a backup of an existing file that will be overwritten as a result of the mv command. We can see that after executing this command stn.sh~ file is created with tilde character(~).
Conclusion
In this tutorial, we covered how we can move one or more files or directories using the mv
command in Linux/Unix with options available in the mv command with suitable examples.