In Linux or Unix, the mv command is used for multiple functions. You can use the mv command to move files or directories from one place to another or it can be used to rename a file or directory.
Today in this article we will explain how to use the mv command with some examples.
Syntax of mv command
How to use mv command, the syntax is given below –
mv [options] Source Destination
It means moving or renaming a file or directory from source to destination.
You can see a list of options on the manual page of this command. Now use the following command to see the options –
man mv
How to rename a file
Suppose we have a file i.e. file1.txt
and you want to rename it to testfile.txt
. Use the following command to rename it –
mv file1.txt testfile.txt
If testfile.txt
already exists then this command will overwrite its content otherwise a new file with the name testfile.txt
will be created and the source file will be deleted.
How to rename a directory in Linux
If you want to rename a directory then use the command as it is given below –
mv old_dir new_dir
Suppose we have a directory with the name dir1
and you want to rename it to new_dir
then use –
mv dir1 new_dir
How to move a file to a directory
Use the following command to move the file testfile.txt
to the directory dir
–
mv testfile.txt dir
Once this command gets executed testfile.txt
will be moved to dir
you can verify this by using the given command-
ls dir
How to move multiple files to a directory
Let’s say you have multiple files file1.txt
file2.txt
file3.txt
and you want to move them into a directory dir
then use the following command in your terminal –
mv file1.txt file2.txt file3.txt dir
How to move a directory to another directory
If you want to move a directory dir1
to dir
then use the following command in the terminal –
mv dir1 dir
Using option -i
with the mv command
By default, the mv command overwrites the destination file or directory without prompting you. If you want to display a confirmation message before it overwrites then you should use the -i
option with the mv command.
For example –
mv -i file1.txt testfile.txt
Conclusion
To see more options that you can use with the mv command see its manual page. If you have a query then write us in the comments below.