The mv command in Linux allows you to move a file from one location to another. Also, we don’t really have a rename command in Linux. Instead, we move files from one name to another. This is facilitated by the “mv” command which stands for move. For basic usage, you will find it very straightforward but it does have some options that make life easier when dealing with multiple files.
Using the mv command in Linux
Alright, let’s begin with the basics. To move or rename a file, you can use the without any options.
root@HowLinux:~# mv file1 newfile
In the above case, if a file named newFile exists, by default the command will overwrite the file. Let’s play around with some more mv command options.
Ask before overwrite with the -i or –interactive option
If a file already exists the command will simply overwrite the file without permission. If you want the mv command to ask you for permission before it overwrites a file, we can make sue of the -i option. Let’s see how it works.
tutorial@HowLinux:~$ mv -i file2 newFile
mv: overwrite 'newFile'?
In the above screenshot, you notice the command prompts you before overwriting the newFile. You can type either “yes” or “no” in the prompt to confirm overwrite or skip it.
Don’t overwrite any file with the use of -n or –no-clobber options
Let’s say you’re moving a lot of files and don’t want any existing files to be overwritten. Now you could let the prompt ask you for every file, or just use the -n option. This option skips the movement of any file where the fileName exists in the target directory.
tutorial@HowLinux:~$ mv -n file1 newFile
With the above command option used, you will notice that the file did not move because there was an existing file with the same name newFile. The command simply does nothing when there is a duplicate file.
Creating file backups using the -b or –backup option
The backup option with the mv command in Linux allows you to create a backup file of an existing file. The default suffix is the tilde (~) but you can change it with the -S or –suffix= option.
tutorial@HowLinux:~$ mv -b file1 newFile
Conclusion
We had a quick look at the mv command that allows us to move and rename files. We also understood how backup files can be created using the mv command. Make sure you use the –help option that comes with all the commands in Linux to learn more about the command.