Moving(renaming) Files with mv Command on GNU/Linux

For a complete reference of mv command please refer to coreutils documentation installed on your system or refer to https://www.gnu.org/software/coreutils/manual/coreutils.html#mv-invocation. Here we will cover most important aspects of mv command with some examples.

mv command is used to move(cut and paste) or rename files. There is no separate command for renaming files on GNU/Linux. Given below is synopsis of mv command:

mv [option]… [-T] source dest
mv [option]… source… directory
mv [option]… -t directory source…

If two filenames are given then mv will either rename first file to second filename or overwrite second file. For example, consider we have a file called f in a directory. If we give a command mv f g whree g is absent then f will be renamed to g. However, if g is present then it will be overwritten. If last argument is a path then all other path arguments coming before that will be moved to last path. For example, mv f1 f2 dir dir1/ will move files f1 and f2 along with directory dir to dir1.

Warning: Avoid specifying a source name with a trailing slash, when it might be a symlink to a directory. Otherwise, mv may do something very surprising, since its behavior depends on the underlying rename system call. On a system with a modern Linux-based kernel, it fails with errno=ENOTDIR. However, on other systems (at least FreeBSD 6.1 and Solaris 10) it silently renames not the symlink but rather the directory referenced by the symlink.

Note: mv will only replace empty directories in the destination. Conflicting populated directories are skipped with a diagnostic.

Now let us see some of the most useful options of mv command.

Creating backup of existing files

You can pass -b or --backup=[method] options to mv to achieve this. Backup methods have been discussed in https://ashtavakra.org/blog/?p=47 with cp command.

Forcing mv

With -f or --force mv will not prompt the you before removing a destination file. If you specify more than one of the -i, -f, -n options, only the final one takes effect.

Interactive mv

With -i or --interactive mv will prompt whether to overwrite each existing destination file, regardless of its permissions. If the response is not affirmative, the file is skipped.

Not overwriting files in destination

With -n or --no-clobber mv will not overwrite existing files.

With this we come to end to most useful options of mv command. See you in next post.

Leave a comment

Your email address will not be published. Required fields are marked *