Count S3 objects and total their size
📑 On this page
Part 41 of AWS from Zero. This lesson keeps the scope to one S3 behavior you can verify from the terminal.
What we are learning
A query can turn an object listing into a quick inventory summary without a separate script.
Before you run it
aws sts get-caller-identity
REGION="ap-south-1"
BUCKET="replace-with-your-private-demo-bucket"Use a private general purpose bucket that you own. Replace every placeholder before running a write or delete command.
The command
aws s3api list-objects-v2 \
--bucket "$BUCKET" \
--query "{ObjectCount:length(Contents),TotalBytes:sum(Contents[].Size)}"A successful configuration command may return no output. Treat inspection as a separate required step.
Inspect the result
aws s3api list-objects-v2 \
--bucket "$BUCKET" \
--prefix "reports/" \
--query "{ObjectCount:length(Contents),TotalBytes:sum(Contents[].Size)}" \
--output tableThe count and sum apply to the objects returned by the command after prefix and pagination behavior.
One tiny variation
aws s3 ls "s3://$BUCKET/" --recursive --summarizeThe high-level command prints a human-oriented total. The API query is easier to compose into scripts.
Common mistake
For very large buckets, a live listing is not a cheap analytics system. S3 Inventory is usually better for repeated full-bucket reporting.
Cleanup
# This lesson does not require an additional persistent resource.
aws s3api head-bucket --bucket "$BUCKET"Keep the shared demo bucket for the next lesson, or remove only the configuration and objects created here.
Next, we will learn Upload an S3 object with a SHA-256 checksum.