Move Files With the mv Command in Linux, With Examples

Linux Move File mv

This article will walk you through moving files in Linux with the mv command, with examples and tips on moving files safely.

mv Syntax

Moving files is done using the mv command, which has the following syntax

mv OPTIONS SOURCE DESTINATION

Note that:

  • OPTIONS is a list of options from the below table
  • SOURCE is the path to the file you wish to move
  • DESTINATION is the path to the destination you want to move the file 2
    • This can include a new file name or simply be the path to a destination folder
    • mv will move SOURCE into DESTINATION if DESTINATION is a directory (or a link to a directory)
      • If DESTINATION is not a directory, mv will rename SOURCE to DESTINATION

Common mv Options

Here are some of the commonly used options when running mv, from the manual:

-b Make a backup of each existing destination file
-f, –force Do not prompt before overwriting
-i, –interactive Prompt before overwrite
-n, –no-clobber Do not overwrite an existing file
-u, –update Move only when the SOURCE file is newer than the destination file or when the destination file is missing.
-v, –verbose Explain what is being done

Additional options can be found in the mv manual by running:

man mv

Examples

Move file1 into directory1:

mv file1 directory1/

Rename file1 to file2:

mv file1 file2

Move file1 into directory1 and rename it to file2:

mv file1 directory1/file2

Move directory1 into directory2:

mv directory1/ directory2/

In the last example, if directory2 doesn’t exist, directory1 will be renamed to directory2. To only move it, and fail if the directory is not found, run:

mv directory1/ directory2/.

This will ensure directory2 exists before trying to move the file – the dot (.) specifies that the path should exist.

Sometimes it’s better to copy than move

If you’re moving files from one drive from another or over a network, consider copying them and removing the original after verifying the copy was successful.

When you’re working on the Linux command line, you don’t have a trash/recycle bin to recover accidentally deleted files – when they’re gone, they’re gone. If your file move operation fails for some reason, you may lose those files, so copying them instead and making sure they have transferred successfully will mitigate this.

You should also back up your files regularly to protect yourself from data loss.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

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