Flatten Directory Structure | Cododel
CODODELDEV
EN / RU
Back to Deck
[shell]

Flatten Directory Structure

SOURCE Bash
VERSION 1.0
AUTHOR Cododel

A Bash script that flattens nested directory structures by moving all files from subdirectories to the root level. Automatically handles filename conflicts and cleans up empty directories.

Features

  • Recursive file moving: Finds all files in nested subdirectories
  • Conflict resolution: Automatically renames duplicates with _1, _2, etc.
  • Extension preservation: Maintains file extensions when renaming
  • Empty directory cleanup: Removes empty subdirectories after moving
  • Safe operations: Uses absolute paths to prevent errors

Use Case

Perfect for cleaning up messy download folders, organizing extracted archives, or consolidating scattered files:

Terminal window
# Flatten a messy downloads folder
./flatten-dirs.sh ~/Downloads/project
# Consolidate extracted archive
./flatten-dirs.sh ./extracted_files
# Clean up nested photo directories
./flatten-dirs.sh ~/Pictures/vacation

Before & After Example

Before:

my-folder/
├── file1.txt
├── subdir1/
│ ├── file2.txt
│ └── file1.txt (conflict!)
└── subdir2/
└── nested/
└── file3.jpg

After:

my-folder/
├── file1.txt
├── file1_1.txt (renamed to avoid conflict)
├── file2.txt
└── file3.jpg

How It Works

  1. Validation: Checks if directory exists
  2. Absolute path: Converts input to absolute path
  3. File discovery: Finds all files at depth ≥2
  4. Conflict detection: Checks for existing files with same name
  5. Smart renaming: Adds _N suffix before extension if conflict
  6. Moving: Relocates files to root directory
  7. Cleanup: Removes empty subdirectories

Usage

Terminal window
# Basic usage
./flatten-dirs.sh <directory>
# Example
./flatten-dirs.sh ~/Downloads/nested_folder

Output Example

Moved: /path/to/folder/subdir/file.txt -> /path/to/folder/file.txt
Moved: /path/to/folder/another/file.txt -> /path/to/folder/file_1.txt
Moved: /path/to/folder/deep/nested/image.jpg -> /path/to/folder/image.jpg
Directory structure flattened

Source Code

flatten-dirs.sh

#!/bin/bash
# Check if directory is provided
if [ $# -ne 1 ]; then
echo "Usage: $0 <directory>"
exit 1
fi
# Check if directory exists
if [ ! -d "$1" ]; then
echo "Error: Directory '$1' does not exist"
exit 1
fi
# Convert to absolute path
target_dir=$(realpath "$1")
# Find all files in subdirectories and move them to root
find "$target_dir" -type f -mindepth 2 | while read -r file; do
filename=$(basename "$file")
dest="$target_dir/$filename"
# Handle filename conflicts
counter=1
while [ -f "$dest" ]; do
base="${filename%.*}"
ext="${filename##*.}"
if [ "$base" = "$ext" ]; then
# File has no extension
dest="$target_dir/${base}_${counter}"
else
# File has extension
dest="$target_dir/${base}_${counter}.${ext}"
fi
((counter++))
done
# Move the file
mv "$file" "$dest"
echo "Moved: $file -> $dest"
done
# Remove empty directories
find "$target_dir" -type d -mindepth 1 -empty -delete
echo "Directory structure flattened"

Safety Notes

  • ⚠️ This operation modifies your filesystem
  • 🔒 Consider making a backup before running
  • 📝 Review the output to see which files were moved
  • 🗑️ Empty directories are permanently deleted
[ ▲ 0 ]