Renaming or Moving Files
As we mentioned previously, a file's path is both its name and its location, so renaming a file is really the same as moving a file. In Unix, to move is to rename, and to rename is to move. When you move a file from one directory to another, you are removing the file's name from the first directory and adding it to the list of files in the second directory. You are actually modifying the directory, not the file.
To move or rename a single file or directory:
- mv oldpath newpath
If the final element of newpath does not exist, then the old file is moved/ renamed to the new path. For example, if newpath is food/pizza/toppings and toppings. does not exist, then the old file is renamed toppings. If food or food/pizza did not exist, you would get an error.
If newpath is an existing directory, then the old file is moved into the destination directory.
If you add a trailing / to the destination directory name, mv makes sure that it is in fact a directory (you get an error if it is not).
If newpath is an existing file, then mv silently attempts to overwrite the old file (you can make it ask you first, with the -i option). You cannot overwrite directories. If there is an existing directory where you want to move something, you must rename or delete the existing directory first.
To move several files at once:
- mv path1 path2 path3 destinationpath
The mv command handles arguments in a manner very similar to that of the cp command described above.
If the mv command is used with more than two arguments, it assumes that the final argument is a directory name and moves all the earlier files into that directory. Table 5.2 shows the options for the mv command.
Table 5.2. Options for mv
Inquire before overwriting existing files.
Force no warnings when overwriting files (that is, you don't want to be notified about files' being changed).