mv command in Linux is used to move files from one directory to another. This is similar to cut-paste operation. mv command can also be used to rename files.
$ mv [OPTION]...SOURCE...Directory
The SOURCE here means all the files that you want to move and the last argument must be a Directory where you want to move the files.
$mv notes.txt D1
will move the file notes.txt to directory D1.
$cp notes.txt read.c write.c /home/baljit/D2
will move the files notes.txt, read.c and write.c to directory D2 which is inside /home/baljit directory.
Note: You can move multiple files at the same time to a Directory but you can not move single file to multiple Directories at the same time.
mv command can also rename files. To do this write the new file name instead of writing the target directory name. For example
There is a file new in the current working directory. Next, we use mv command to rename it to new1. Note that the second argument is the new file name and not a directory name. The second ls command shows that the name is changed to new1.
-b: option creates a backup file in the destination directory. This happens only if a file with the same name is already in the destination directory. One can identify the backup file with the tilde(~) symbol.
-f: Suppose you try to copy a file ‘new’ into a directory D1 which already contains a file with the name ‘new’ and this file within D1 is non-writable (remove the write permission using chmod command). So if you try to move new into D1 you will see this
Now, you need to explicitly write ‘y’ and press enter to move it. The alternate approach to avoid this is simple use the -f option as
$mv -f new D1
-i: option gives a prompt in case a file with the same name already exists in the destination directory. For example:
Since, f1 already exists in D2, so when we use cp with -i option to copy file f1 again into D2 the system prompts a message to confirm the overwrite. Now if you are sure you want to overwrite then press ‘y’ else ‘n’ and then ‘enter’ key.
-t: option helps to change the order of Source and Destination. For example:
we specify the destination directory D1 before the source file f3.
Q1. You created a file “note.txt” and wrote some content into it. Later you realized that the name must be “notes.txt”. Correct the name of the file without affecting the contents within it.
Q2. There is a file “hello” and a directory “Dest” in your current working directory. Move the file “hello” into directory “Dest” but the name after moving must be changed to “hello_copy”.