BASH

Recursively Clean Up Project Dependencies Directories

Free up disk space by recursively finding and deleting `node_modules`, `vendor`, or other specified dependency directories across multiple projects.

#!/bin/bash
# Usage: ./cleanup_deps.sh [start_directory]
# Example: ./cleanup_deps.sh ~/Projects

START_DIR="${1:-.}" # Defaults to current directory if not provided

# List of directories to remove
# Add or remove directory names as needed. Ensure they are common patterns.
DIRS_TO_CLEAN=("node_modules" "vendor" "target" ".gradle")

echo "Starting cleanup in directory: $START_DIR"
echo "Looking for and removing: ${DIRS_TO_CLEAN[*]}"

# Counter for deleted directories
DELETED_COUNT=0
DELETED_SIZE=0

for DIR_NAME in "${DIRS_TO_CLEAN[@]}"; do
    echo "Searching for '$DIR_NAME' directories..."
    # Using find to locate directories and then loop through them
    find "$START_DIR" -type d -name "$DIR_NAME" -prune | while read -r found_dir;
    do
        if [ -d "$found_dir" ]; then
            DIR_SIZE=$(du -sh "$found_dir" | awk '{print $1}')
            # Uncomment the echo below for a dry run without actual deletion
            # echo "[DRY RUN] Would delete: $found_dir (Size: $DIR_SIZE)"
            
            echo "Deleting: $found_dir (Size: $DIR_SIZE)"
            rm -rf "$found_dir"
            if [ $? -eq 0 ]; then
                DELETED_COUNT=$((DELETED_COUNT+1))
                # This size aggregation is approximate as `du -sh` output is human-readable
                # For precise calculation, use `du -s` and sum in bytes, then convert.
                # For simplicity here, we just count the entries.
            else
                echo "Failed to delete: $found_dir"
            fi
        fi
    done
done

echo "
Cleanup complete."
echo "Total directories deleted: $DELETED_COUNT"
# echo "Total space reclaimed: (Approx) $DELETED_SIZE"
How it works: This script helps reclaim disk space by finding and deleting large dependency directories like `node_modules` (for Node.js projects) or `vendor` (for PHP Composer projects) recursively. It takes an optional starting directory, otherwise defaults to the current one. It iterates through a predefined list of directory names, uses `find` to locate them, and then `rm -rf` to delete them. Before deletion, it reports the size of each directory. This is particularly useful for developers working on many projects.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs