Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Forked from zephraph/clean_node_modules.sh
Created May 12, 2019 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whoisryosuke/838a77249a3c69b7498a1d53b8c5e0f7 to your computer and use it in GitHub Desktop.
Save whoisryosuke/838a77249a3c69b7498a1d53b8c5e0f7 to your computer and use it in GitHub Desktop.
Clean up node_modules
#!/bin/bash
DAYS_SINCE_LAST_CHANGE=14
SEARCH_PATH="./Git"
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