The Unix mv commandThe mv command moves or renames a file. There are several forms of the mv command
- mv filename1 filename2
Renames the file named filename1 to filename2. For example:
linux1% ls cs104 joke Mail OtherStuff www linux1% mv joke my_joke linux1% ls cs104 Mail my_joke OtherStuff www
Be careful using the mv command. If filename2 already exists, then it is deleted!
linux1% ls cs104 joke1 joke2 Mail OtherStuff www linux1% mv joke1 joke2 linux1% ls cs104 joke2 Mail OtherStuff www
In the example above, the file originally named joke1 becomes joke2. The original joke2 is gone forever.
- mv filename directory
In this version of mv, the specified file is moved into the specified directory and keeps its file name:
linux1% ls cs104 hw01 hw02 hw03 linux1% mv joke cs104 linux1% ls cs104 hw01 hw02 hw03 joke
This use of the mv can be confusing if the specified directory does not exist. Then, it becomes the first form of the mv command and the file is given the name of the 'directory' (which doesn't exist), instead of being moved inside the 'directory' (which can't happen, because there is no such directory). For example:
linux1% ls cs104 joke Mail OtherStuff www linux1% mv joke hw01 linux1% ls cs104 hw01 Mail OtherStuff www linux1% ls -l hw01 -rw------- 1 chang faculty 60 Sep 9 12:24 hw01 linux1% ls hw01 hw01
In the example above, there is no hw01 directory in the current directory. So, the mv command simply renames joke into hw01. Notice that the listing shows that after hw01 is created, it is an ordinary file, not a directory. This is especially confusing if you thought (erroneously) that there was a directory called hw01.
This sort of mistake can be avoided by including a backslash '/' at the end of the directory name:
linux1% ls cs104 joke1 joke2 Mail OtherStuff www linux1% mv joke1 cs104/ linux1% ls cs104 joke2 Mail OtherStuff www linux1% ls cs104 hw01 hw02 hw03 joke1 linux1% mv joke2 hw01/ mv: cannot move `joke2' to `hw01/': Not a directory
The last mv command resulted in an error and does not rename joke2 into hw01.
- mv filename1 filename2 filename3 ... directory
This form of the mv command moves several files into the specified directory. (The directory is always the last filename given.) In the following example, the files joke1, joke2 and joke3 are moved into the cs104 directory:
linux1% ls cs104 joke1 joke2 joke3 Mail OtherStuff www linux1% ls cs104 hw01 hw02 hw03 linux1% mv joke1 joke2 joke3 cs104/ linux1% ls cs104 hw01 hw02 hw03 joke1 joke2 joke3