通过AWS CLI获取S3桶大小的Shell脚本



我有这个脚本,它获取AWS中的所有桶及其大小。但是,当我运行的脚本,其获取桶,但当运行的循环获取的大小,它抛出错误。谁能指出我错在哪里吗?因为当我为单个桶运行awscli命令时,它抓取大小没有任何问题。期望的输出如下所示,但对于所有桶,我只获取了一个桶。期望ouptut:

aws --profile aws-stage s3 ls s3://<bucket> --recursive --human-readable --summarize | awk END'{print}'
Total Size: 75.1 KiB

错误:

Bucket name must match the regex "^[a-zA-Z0-9.-_]{1,255}$" or be an ARN matching the regex "^arn:(aws).*:(s3|s3-object-lambda):[a-z-0-9]*:[0-9]{12}:accesspoint[/:][a-zA-Z0-9-.]{1,63}$|^arn:(aws).*:s3-outposts:[a-z-0-9]+:[0-9]{12}:outpost[/:][a-zA-Z0-9-]{1,63}[/:]accesspoint[/:][a-zA-Z0-9-]{1,63}$"

脚本:

#!/bin/bash
aws_profile=('aws-stage' 'aws-prod');
#loop AWS profiles
for i in "${aws_profile[@]}"; do
echo "${i}"
buckets=$(aws --profile "${i}" s3 ls s3:// --recursive | awk '{print $3}')
#loop S3 buckets
for j in "${buckets[@]}"; do
echo "${j}"
aws --profile "${i}" s3 ls s3://"${j}" --recursive --human-readable --summarize | awk END'{print}'
done
done

试试这个:

#!/bin/bash
aws_profiles=('aws-stage' 'aws-prod');
for profile in "${aws_profiles[@]}"; do
echo "$profile"
read -rd "n" -a buckets <<< "$(aws --profile "$profile" s3 ls | cut -d " " -f3)"
for bucket in "${buckets[@]}"; do
echo "$bucket"
aws --profile "$profile" s3 ls s3://"$bucket" --human-readable --summarize | awk END'{print}'
done
done

问题是你的buckets是一个字符串,而不是一个数组。