Downloading the latest file in an S3 bucket using AWS CLI?

Abe Miessler picture Abe Miessler · Jul 14, 2016 · Viewed 34.2k times · Source

I have an S3 bucket that contains database backups. I am creating a script that I would like to download the latest backup (and eventually restore it somewhere else), but I'm not sure how to go about only grabbing the most recent file from a bucket.

Is it possible to copy only the most recent file from a s3 bucket to a local directory using AWS CLI tools?

Answer

JBaczuk picture JBaczuk · Sep 11, 2017

And here is a bash script create based on @error2007s's answer. This script requires your aws profile and bucket name as variables, and downloads the latest object to your ~/Downloads folder:

#!/bin/sh
PROFILE=your_profile
BUCKET=your_bucket

OBJECT="$(aws s3 ls --profile $PROFILE $BUCKET --recursive | sort | tail -n 1 | awk '{print $4}')"
aws s3 cp s3://$BUCKET/$OBJECT ~/Downloads/$OBJECT --profile $PROFILE