Created
April 4, 2025 12:58
-
-
Save asmattic/8b7e4579bd87bcb520a308580c4afd8e to your computer and use it in GitHub Desktop.
Recursively removes all node modules directories within a given directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
echo -e "\nFind and optionally delete all top level node_modules in a specific directory.\n" | |
# Initialize an array to store paths | |
NODE_MODULES_PATHS=() | |
while IFS= read -r line; do | |
size=$(echo "$line" | awk '{print $1}') | |
path=$(echo "$line" | awk '{print $2}') | |
# Skip if directory is nested inside another node_modules | |
if [[ ! $path =~ /node_modules/.*/node_modules$ ]] && [[ $size != "0B" ]]; then | |
echo "$size $path" | |
NODE_MODULES_PATHS+=("$path") | |
fi | |
done < <(find . -type d -name "node_modules" -prune -exec du -sh {} \; | sort -hr) | |
echo -e "\nTotal size of significant node_modules:" | |
find . -type d -name "node_modules" -prune -exec du -s {} \; | awk '{ total += $1 } END { printf "%.1fG\n", total/1024/1024 }' | |
# Prompt user to delete the node_modules directories | |
echo -e "\nFound ${#NODE_MODULES_PATHS[@]} significant node_modules directories." | |
echo "Would you like to delete these node_modules directories? (y/n)" | |
# Debug info | |
echo "Waiting for your input... (Press y or n and then Enter)" | |
# Make sure we're reading from the terminal directly | |
REPLY="" | |
if [ -t 0 ]; then | |
read -r REPLY </dev/tty | |
else | |
read -r REPLY | |
fi | |
echo "You entered: '$REPLY'" | |
# Delete the node_modules directories if user confirms | |
if [[ $REPLY =~ ^[Yy]$ ]]; then | |
echo "Proceeding with deletion..." | |
for path in "${NODE_MODULES_PATHS[@]}"; do | |
echo "Deleting $path" | |
sudo rm -rf "$path" | |
done | |
echo -e "\nVerifying deletion..." | |
new_size=$(find . -type d -name "node_modules" -prune -exec du -s {} \; | awk '{ total += $1 } END { printf "%.1fG\n", total/1024/1024 }') | |
if [[ $new_size == "0.0G" ]]; then | |
echo "All node_modules directories were successfully deleted!" | |
else | |
echo "Remaining node_modules size: $new_size" | |
echo "Some directories might require additional permissions to delete." | |
fi | |
else | |
echo "Operation cancelled. No directories were deleted." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment