-
-
Save tawanorg/2e759ed20b230cd97af1a6469afea6b3 to your computer and use it in GitHub Desktop.
A shell script to clean up all node_modules in projects that haven't been touched in a couple weeks.
This file contains 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 | |
DAYS_SINCE_LAST_CHANGE=14 # If a project hasn't been touched in this long its node_modules will be deleted | |
SEARCH_PATH="./Git" # Update this to the path where your code is stored | |
TOTAL_BYTES_REMOVED=0 | |
Mb=1000000 | |
Kb=1000 | |
node_modules=$(find $SEARCH_PATH -name "node_modules" -type d -prune) | |
HAS_RECENTLY_CHANGED_FILES=false | |
check_for_changed_files () { | |
local files=$(find $1 -ctime -$DAYS_SINCE_LAST_CHANGE -not -path "**/.git/**" -not -path "**/node_modules/**") | |
if [ -z "$files" ]; then | |
HAS_RECENTLY_CHANGED_FILES=false | |
else | |
HAS_RECENTLY_CHANGED_FILES=true | |
fi | |
} | |
for path in $node_modules | |
do | |
parent_path=$(dirname $path) | |
check_for_changed_files $parent_path | |
if [ "$HAS_RECENTLY_CHANGED_FILES" = false ]; then | |
echo "Cleaning $path" | |
removed=$(du -sh $path | cut -f1) | |
rm -rf $path | |
if [[ $removed == *"M" ]]; then | |
TOTAL_BYTES_REMOVED=$(echo "$TOTAL_BYTES_REMOVED + (${removed/M/} * $Mb)" | bc) | |
fi | |
if [[ $removed == *"K" ]]; then | |
TOTAL_BYTES_REMOVED=$(echo "$TOTAL_BYTES_REMOVED + (${removed/K/} * $Kb)" | bc) | |
fi | |
if [[ $removed == *"B" ]]; then | |
TOTAL_BYTES_REMOVED=$(echo "$TOTAL_BYTES_REMOVED + ${removed/B/}" | bc) | |
fi | |
fi | |
done | |
if (( $(echo "$TOTAL_BYTES_REMOVED > $Mb" | bc -l) )); then | |
formatted_bytes="$(echo "$TOTAL_BYTES_REMOVED / $Mb" | bc)M" | |
elif (( $(echo "$TOTAL_BYTES_REMOVED > $Kb" | bc -l) )); then | |
formatted_bytes="$(echo "$TOTAL_BYTES_REMOVED / $Kb" | bc)K" | |
else | |
formatted_bytes="${TOTAL_BYTES_REMOVED}B" | |
fi | |
echo "Bytes removed: $formatted_bytes" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment