Skip to content

Instantly share code, notes, and snippets.

@br3ndonland
Last active November 22, 2024 20:52
Show Gist options
  • Save br3ndonland/102d2e01ce31c0aa24323d01ec76e79f to your computer and use it in GitHub Desktop.
Save br3ndonland/102d2e01ce31c0aa24323d01ec76e79f to your computer and use it in GitHub Desktop.
AWS S3 bucket names
#!/usr/bin/env bash
# get a list of S3 bucket names
# -----------------------------
# aws returns the bucket creation date and name:
# 2022-02-22 22:22:22 bucket-name
# additional logic is required to produce an array of names.
# pure bash
# https://github.com/dylanaraps/pure-bash-bible/issues/113
# "read returns 1 when everything is read, which is convenient when used in a while loop"
# note that, in this case, `read -d "\n"` and `IFS=$'\n' read -d ""` may be different
BUCKETS="$(aws s3 ls)"
IFS=$'\n' read -d "" -ra BUCKETS_ARRAY <<<"$BUCKETS" || true
for i in "${!BUCKETS_ARRAY[@]}"; do
BUCKETS_ARRAY[i]="${BUCKETS_ARRAY[i]##* }"
done
echo "Pure Bash: ${#BUCKETS_ARRAY[@]} buckets"
# pure bash 4+ using mapfile
# https://github.com/dylanaraps/pure-bash-bible/issues/38
if [[ "${BASH_VERSINFO[0]}" -lt 4 ]]; then
echo "This example requires Bash 4+"
else
BUCKETS="$(aws s3 ls)"
mapfile -t BUCKETS_ARRAY <<<"$BUCKETS"
for i in "${!BUCKETS_ARRAY[@]}"; do
BUCKETS_ARRAY[i]="${BUCKETS_ARRAY[i]##* }"
done
echo "Pure Bash 4+ using mapfile: ${#BUCKETS_ARRAY[@]} buckets"
fi
# bash 4+ using mapfile with cut
if [[ "${BASH_VERSINFO[0]}" -lt 4 ]]; then
echo "This example requires Bash 4+"
else
BUCKETS="$(aws s3 ls | cut -d ' ' -f 3)"
mapfile -t BUCKETS_ARRAY <<<"$BUCKETS"
echo "Bash 4+ using mapfile with cut: ${#BUCKETS_ARRAY[@]} buckets"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment