How to Move or Rename a File in Bash

The command used to move or rename a file in Bash is mv. This command allows you to change the location of a file or rename it within the same directory. Below, we will explore the syntax of the mv command, along with examples and options.

Basic Syntax of the mv Command

The basic syntax for the mv command is as follows:

mv [options] source destination

In this syntax:

  • source is the path to the file you want to move or rename.
  • destination is the new location or new name for the file.
  • [options] are optional flags that modify the behavior of the command.

Example of Moving a File

Here’s a simple example of using the mv command to move a file:

mv file1.txt /path/to/destination/

In this example:

  • The command moves file1.txt to the specified directory /path/to/destination/.
  • If the destination directory does not exist, an error will be returned.

Example of Renaming a File

You can also use the mv command to rename a file:

mv old_filename.txt new_filename.txt

In this example:

  • The command renames old_filename.txt to new_filename.txt within the same directory.
  • If new_filename.txt already exists, it will be overwritten without any warning.

Using Options with the mv Command

The mv command supports various options to customize its behavior. Here are some commonly used options:

1. -i Option

The -i option prompts you for confirmation before overwriting an existing file:

mv -i old_filename.txt new_filename.txt

In this example:

  • If new_filename.txt already exists, the command will ask for confirmation before overwriting it.

2. -u Option

The -u option moves the file only if the source file is newer than the destination file or if the destination file does not exist:

mv -u file1.txt /path/to/destination/

In this example:

  • The command will only move file1.txt if it is newer than the existing file in the destination or if the destination file does not exist.

3. -v Option

The -v option enables verbose mode, which provides detailed output of the operation:

mv -v file1.txt /path/to/destination/

In this example:

  • The command will display a message indicating that file1.txt is being moved to the specified destination.

Conclusion

The mv command is an essential tool in Bash for moving and renaming files. By understanding its syntax and various options, you can effectively manage your files and directories. Whether you need to relocate a file to a different directory or rename it, the mv command provides the necessary functionality to accomplish these tasks efficiently.