The mv command in Linux: moving and renaming files

Introduction

The mv command is one of the most used tools in the Linux command line for moving and renaming files and directories. Although its main function seems simple, understanding its options and behaviors avoids surprises, especially when working with absolute paths, symbolic links, or different filesystems.

Basic Syntax

The simplest form of mv follows the pattern:

  • mv source destination

Where source is the file or directory you want to move and destination can be a new name (to rename) or an existing directory (to move it inside). If destination is an existing directory, mv places the source inside it, preserving its original name.

Most Used Options

  • -i (interactive): prompts for confirmation before overwriting an existing file.
  • -f (force): overwrites without asking, canceling the effect of -i.
  • -v (verbose): shows each operation performed, useful in scripts or debugging.
  • -u (update): moves only when the source is newer than the destination or when the destination does not exist.
  • --backup=CONTROL: creates backups of files that would be overwritten according to the specified mode (numbered, existing, simple, never).

Practical Examples

Renaming a file:

  • mv informe.txt informe_final.txt

Moving a file to another directory:

  • mv foto.jpg /home/usuario/imagenes/

Moving multiple files at once:

  • mv *.pdf documentos/

Using the interactive option to avoid accidental overwrites:

  • mv -i borrador.docx documentos/borrador.docx

Creating a backup before overwriting:

  • mv --backup=numbered configuracion.cfg /etc/

Tips and Tricks

When working across different filesystems, mv can behave like a copy followed by a deletion; therefore, on mounts with options noexec or nosuid, it may fail. In those cases, using cp followed by rm is safer.

To rename directories that contain spaces in their names, you need to enclose the path in quotes or use backslash escaping:

  • mv 'proyecto antiguo' 'proyecto_nuevo'

In scripts, combining -v with --backup=simple allows generating a clear log of which files were moved and which backups were created.

Finally, remember that mv does not alter the permissions or extended attributes of files; it preserves the same ones as the source, unless the destination filesystem has different restrictions.

Conclusion

Mastering mv is essential for any Linux user or administrator. Its simplicity hides a set of options that, when known, allow performing file operations safely and efficiently. Practicing with the examples and options described will help you avoid common mistakes and make the most of this fundamental command.

This post is also available in ESPAÑOL.

Esta obra está bajo una Licencia Creative Commons Atribución 4.0 Internacional para Francesc Roig francesc@vivaldi.net .