In this guide, you will learn how to use the Linux/Unix mv
command. Linux mv command has 2 distinct functionalities depending on how it’s used.
- It can be used to rename a file or a folder
- It can be used for moving a file or a folder from one location to another
Table of Contents
Using mv command to rename a file or a directory
To rename a file using mv, the 2 files (The original and renamed file) must be in the same location
The syntax for renaming a file or a directory is as follows
# mv file_name new_file_name
For example, I have a file called linux-for-beginners
and I want to rename it to unix-for-beginners
# mv linux-for-beginners unix-for-beginners
You can further verify that the file has been renamed using the ls
command. The output is shown below
As observed, the original file has been renamed. The command and syntax remain the same for directories.
Using mv to move a file or a directory
Having looked at how to rename a file /directory, let’s see how you can move a file from one directory to another.
The syntax for this is as follows
# mv [option] file /path/to/destination/directory
For example , to move the file unix-for-beginners
to the /opt
directory, run
$ mv unix-for-beginners /opt
The syntax remains the same for moving directories. In the example below , the directory tutorials
is being moved to /opt
directory
mv command options
The mv command can be accompanied by a variety of options. Let’s have a look
-i (Interactive)
This option prompts the user for confirmation before moving a file that would overwrite a pre-existing file with the same name. In this case, the user must press y to confirm or overwrite.
Sample output
-n (no-clobber)
The -n
option prevents a file from being overwritten. That is , you can rename a file to match another file and still keep the contents of the pre-existing file. In this example, we have 2 files file1.txt
and file2.txt
. We are going to rename file1.txt
to file2.txt
using the -n
attribute but still retain the contents of file2.txt
Sample output
-v (verbose)
the -v
option displays the status of the activity taking place when mv
is running. The output of the activity is printed on the terminal as shown
Sample output
-u (update)
The -u
option updates the destination file only if the source file has newer content or the destination file is missing.
Checking version of mv command
To check the version of mv
run the command
$ mv --version
Sample output
Getting help with mv command
For more mv command options run the command
$ mv --help
Sample output