Delete one S3 object safely
📑 On this page
Part 20 of AWS from Zero. Today we delete exactly one object.
What we are learning
For a non-versioned bucket, deleting an object is permanent. A careful command-line flow is: inspect, back up when needed, delete, then verify.
Before you run it
REGION="ap-south-1"
BUCKET="aws-zero-delete-one-12345"
KEY="notes/important.txt"
aws s3api create-bucket \
--bucket "$BUCKET" \
--region "$REGION" \
--create-bucket-configuration LocationConstraint="$REGION"
echo "important demo file" > important.txt
aws s3 cp important.txt "s3://$BUCKET/$KEY"Inspect the exact key first:
aws s3api head-object --bucket "$BUCKET" --key "$KEY"Optional backup
aws s3 cp "s3://$BUCKET/$KEY" important-backup.txtDelete the object
aws s3api delete-object \
--bucket "$BUCKET" \
--key "$KEY"Verify the result
aws s3api list-objects-v2 \
--bucket "$BUCKET" \
--prefix "$KEY" \
--query "Contents[].Key" \
--output textNo returned key means the current object is no longer listed.
One tiny variation
The high-level equivalent is shorter:
aws s3 rm "s3://$BUCKET/$KEY"Use s3api delete-object when you need low-level options such as a specific version ID.
Common mistake
S3 delete operations are idempotent for a missing key: deleting a key that is already absent can still return success. Always verify the exact bucket and key before and after deletion.
Versioned buckets behave differently. A normal delete usually creates a delete marker instead of permanently removing old data. We will see that shortly.
Cleanup
aws s3api delete-bucket --bucket "$BUCKET" --region "$REGION"
rm important.txt important-backup.txtNext, we will delete several known keys in one request.