BudiBadu Logo
Samplebadu

Bash by Example: Move Files

Bash 5.0+

Moving and renaming files using the mv command for file operations, understanding the dual purpose of mv for both moving files between directories and renaming files in place, using the -i flag for interactive confirmation to prevent accidental overwrites, implementing atomic rename operations, and handling bulk file moves with loops.

Code

#!/bin/bash

touch file.txt
mkdir -p destination

# 1. Rename a file (Move to same dir with new name)
mv file.txt renamed.txt
echo "Renamed file.txt to renamed.txt"

# 2. Move to a directory
mv renamed.txt destination/
echo "Moved to destination/"

# 3. Move and rename
mv destination/renamed.txt destination/final.txt

# 4. Move multiple files
touch a.txt b.txt
mv a.txt b.txt destination/

# Check result
ls destination/

rm -rf destination

Explanation

The mv command serves two purposes: moving files to a new location and renaming files. In Unix, renaming is simply moving a file to a new name within the same directory.

Unlike cp, mv does not create a copy; it updates the file path. This is much faster, especially for large files on the same filesystem, as it only updates the filesystem index (inode).

Like rm and cp, you can use -i to prompt before overwriting an existing destination file.

Code Breakdown

7
Renaming. The source is file.txt and the destination is renamed.txt.
11
Moving. If the destination is a directory, the file is moved inside it, keeping its original filename.
19
Moving multiple files. The last argument destination/ must be a directory.