Linux Commands Series 6 : mv command


In the previous tutorial, we learnt about the cp command, now it is time for a similar command : mv

mv command stands for "move", it has a crucial difference with the cp command, it is the fact that the file/directory moved does not exist anymore at its source, it is defintely moved at the new destination

There are two main uses for mv command : moving files/directories or renaming them

  1. Moving a file to a directory :

mv file1.txt project1

mv command file to directory

we moved file1.txt from Linux directory to project1 directory, note that file1.txt disappeared from Linux directory, and moved to project1 directory as shown by ls project1 command

2. Moving a directory to an other directory :

mv project1 project2

mv command directory to an other directory

project1 folder moved from Linux directory into project2 directory

3. Renaming a file :

mv file2.txt file2new.txt

mv command to rename a file

we used mv command to rename file2.txt into file2new.txt, after the command executed, the file1.txt exists no more, and is named file2new.txt, the two files are exactly the same, and have exactly the same metadata as shown in this following screenshot :

mv command file to file

4. Renaming a directory :

mv project3 project3new

mv command to rename a directory

project3 is renamed into an exact replica named project3new, which is shown by the last command ls project3new/

5. When renaming a file/directory to a file/directory name that already exists, you can choose to be on the safe side, and provide mv command with the backup option -b, it will make a backup of the destination file/directory that is there, let's showcase this :

mv command with backup option for destination
  1. ls tip* : the asterik is called a wildcard, the command ls is applied to every file that starts with "tip" followed by anything

  2. mv -b tip1.txt tip2.txt will rename tip1.txt into tip2.txt, overriding the content of tip2.txt, but there is a new file : tips2.txt~ which is a backup file

  3. cat tip2.txt~ will show that it contains the data of the original tip2.txt file, thus tip2.txt data is not lost

6. if you do not like the overwriting behaviour, you can provide mv command with the option -n, as demonstrated in the following :

mv command without overwriting behaviour

the last cat tip3.txt tip4.txt show the same data in the files is still there, so the -n option made mv command uncapable of overwriting tip4.txt file with data from tip3.txt

The -n and -b options are thus good mechanisms to make the mv command safer for its user

This was the essential uses of mv command, if you found the article useful, don't forget to leave a comment, and share it with your friends.

Happy Linux Learning !