How to move a file, group of files, and directories in Linux?


The mv (move) command is used to move one or more files or directories from one directory to another directory using terminal in the Linux/Unix operating system. After using the mv command file is copied from source to destination and source file is removed. The mv command is also used to rename the file.

Syntax

The general syntax of the mv command is as follows

$ mv [OPTION]...[-T] SOURCE DESTINATION...
$ mv [OPTION]...SOURCE... DIRECTORY...
$ mv [OPTION]...-t DIRECTORY SOURCE...

Brief description of options available in the mv command.

Sr.No.Option & Description
1--backup [=CONTROL]
Create backup of destination file
2-b
Create backup file without argument
3-f
Do not prompt before overwriting
4-i, interactive
Prompt before overwriting files
5-n, --no-clobber
Not overwrite an existing file
6-t, --target-directory=DIRECTORY
Move all source arguments into directory
7-T, --no-target-directory
Treat destination as a normal file
8-u, --update
Move when source file is newer than the destination file either destination file is missing
9-v, --verbose
Prompt what is happening
10--help
Displays a help message and then exits.
11--version
It gives info about the version and then exits.

To move a file from a directory and paste it into another directory use the mv command as shown in below.

$ mv file.txt ../snow

Here snow is a directory in which a file will be moved from the current directory after executing the above command.

To move an entire directory to another directory using the mv command without any option the syntax is as follows.

$ mv <SOURCE DIRECTORY> <DESTINATION DIRECTORY>

Suppose snow is a directory which has to move to a shadow directory.

$ mv snow shadow

And the directory will be moved.

Here, we will move a file as well as create a backup file of an existing file in the destination directory that will be used to recover the previous file.

First of all, using the cat command we create a file file.txt and write some contents

$ cat >snow/file.txt

And move into another directory but another file with the same name available in the snow directory then a backup file is created in the snow directory.

$ mv --backup file.txt snow

We can see it using ls -a because just using the ls command hidden files will not prompt.

$ ls -a

Updated on: 01-Jul-2021

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements