Skip to content

Instantly share code, notes, and snippets.

@JoshuaSchlichting
Last active April 1, 2025 18:03
Show Gist options
  • Save JoshuaSchlichting/80848efd37dbc81cb40f0f1f3ff3340d to your computer and use it in GitHub Desktop.
Save JoshuaSchlichting/80848efd37dbc81cb40f0f1f3ff3340d to your computer and use it in GitHub Desktop.
#!/bin/bash
######## ######## ######## ######## ######## ######## ###########
### THIS BASH SCRIPT WILL COMPLETE DELETE *EVERY* OBJECT ####
### INCLUDING HIDDEN VERSIONS FROM AN S3 BUCKET!! ####
######## ######## ######## ######## ######## ######## ###########
BUCKET_NAME="$1"
if [[ -z "$BUCKET_NAME" ]]; then
echo "Usage: $0 <bucket-name>"
exit 1
fi
expected="Delete my objects in $BUCKET_NAME"
read -p "Type EXACTLY: \"$expected\" to confirm: " confirmation
if [[ "$confirmation" != "$expected" ]]; then
echo "Confirmation failed. Nothing was deleted. Probably a good idea. 😌"
exit 1
fi
final_confirmation_sentence="I understand I am deleting all historical versions"
read -p "Type '${final_confirmation_sentence}' to continue: " final_confirmation
if [[ "$final_confirmation" != $final_confirmation_sentence ]]; then
echo "You must type '$final_confirmation_sentence' to continue! Exiting..."
exit 1
fi
echo "Confirmed. Proceeding with deletion from bucket: $BUCKET_NAME"
while :; do
OUTPUT=$(aws s3api list-object-versions --bucket $BUCKET_NAME --max-items 1000)
KEYS=$(echo "$OUTPUT" | jq -r '.Versions[]?, .DeleteMarkers[]? | {Key: .Key, VersionId: .VersionId}' | jq -s '{Objects: .}')
if [ "$(echo "$KEYS" | jq '.Objects | length')" -eq 0 ]; then
echo "No more objects to delete. All clean. 🧼"
break
fi
echo "$KEYS" | aws s3api delete-objects --bucket $BUCKET_NAME --delete file:///dev/stdin
NEXT_TOKEN=$(echo "$OUTPUT" | jq -r '.NextToken // empty')
[ -z "$NEXT_TOKEN" ] && break
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment