Skip to content

Instantly share code, notes, and snippets.

@reaperes
Created October 20, 2023 04:52
Show Gist options
  • Save reaperes/7ed59dd9fdd7782176c9182f57d1ffcc to your computer and use it in GitHub Desktop.
Save reaperes/7ed59dd9fdd7782176c9182f57d1ffcc to your computer and use it in GitHub Desktop.
Remove unnecessary old containers
#!/bin/bash
# Must set container prefix
DELETE_REGEX="^temp-.*"
# protect containers regex
EXCLUDE_REGEX="(?!(jenkins|nginx))"
current=$(date +"%s")
deleteUntil=$(date -d '-3 days' +"%s")
docker ps -q --filter "name=$EXCLUDE_REGEX" --filter "name=$DELETE_REGEX" --format "{{.ID}}" | while read containerId
do
createdAtStr=$(docker inspect -f "{{.Created}}" "$containerId")
createdAt=$(date -d "$createdAtStr" +"%s")
if [ "$createdAt" -lt "$deleteUntil" ]; then
docker rm -f $containerId
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment