Linux commands: mv

By

Learn how the Linux mv command moves a file to a new path, how it doubles as the way you rename files, and how to move several files into a folder at once.

~~~

Once you have a file, you can move it around using the mv command. You specify the file current path, and its new path:

touch pear
mv pear new_pear

The pear file is now moved to new_pear. This is how you rename files and folders. mv -i asks before overwriting an existing file. GNU and BSD/macOS mv both support it.

If the last parameter is a folder, the file located at the first parameter path is going to be moved into that folder. In this case, you can specify a list of files and they will all be moved in the folder path identified by the last parameter:

touch pear
touch apple
mkdir fruits
mv pear apple fruits #pear and apple moved to the fruits folder

Overwriting

mv replaces a file that already exists at the destination. No warning, unless you pass -i:

touch pear
echo 'old' > basket
mv pear basket

basket is now the pear file. The old basket content is gone.

mv -n (no-clobber) skips the move when the destination exists. GNU and BSD/macOS both have it.

Moving a folder

You do not need a recursive flag. mv moves the folder and everything in it:

mkdir fruits
mv fruits pantry

fruits is now called pantry. If pantry already exists as a folder, fruits lands inside it as pantry/fruits.

Be careful with a trailing slash on the destination. mv pear fruits/ only works if fruits is already a folder. If fruits does not exist, that command fails.

When the source and destination sit on different filesystems, mv copies the file and then deletes the original. A power cut in the middle can leave you with both, or with a partial copy.

To copy a file instead of moving it, use cp.

This command works on Linux, macOS, WSL, and anywhere you have a UNIX environment

Tagged: CLI · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about cli: