#!/bin/bash target="s3://your-AWS-bucket-here/" file="" # if you're looking for a specific file extension # you can do something like this instead # while [[ "$target" != *.tgz ]]; do # while there is a slash at the end of the path # i.e. it isn't a file while [[ "$target" == */ ]]; do list=$(aws s3 ls "$target") # create an array of options using the # last "word" in each line of the # output from aws options=() while IFS= read; do options+=( $(echo "$REPLY" | awk '{print $(NF)}') ) done <<< "$list" # select an option and append it select option in "${options[@]}"; do [ -z "$option" ] && exit 1 target="$target$option" file="$option" break done done aws s3 cp $target $file # do something with $file