Australia/Sydney
BlogAugust 3, 2023

Script to Empty and Delete AWS S3 Bucket in One Go

Fahd Mirza

 This script deletes all the objects and version and then S3 bucket itself. Just login to your Linux terminal, make sure you have aws cli configured, and run the following shell script. Also make sure to do chmod +x <script name> to make your script executable.




#!/bin/bash


buckettodelete=$1


if [ -z "$buckettodelete" ] ; then

echo "Usage: $0 <buckettodelete>"

exit 1

fi


# Step 1: Delete objects

aws s3api delete-objects --bucket ${buckettodelete} --delete "$(aws s3api list-object-versions --bucket ${buckettodelete} --query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}')" --output text


# Step 2: Delete markers

aws s3api delete-objects --bucket ${buckettodelete} --delete "$(aws s3api list-object-versions --bucket ${buckettodelete} --query='{Objects: DeleteMarkers[].{Key:Key,VersionId:VersionId}}')" --output text


# Step 3: Delete Bucket

aws s3 rb s3://${buckettodelete}/ --force

Share this post:
On this page

Let's Partner

If you are looking to build, deploy or scale AI solutions — whether you're just starting or facing production-scale challenges — let's chat.

Subscribe to Fahd's Newsletter

Weekly updates on AI, cloud engineering, and tech innovations