Shell 使用 AWS CLI 获取 S3 存储桶大小的脚本

Shell script to fetch S3 bucket size with AWS CLI

我有这个脚本可以获取 AWS 中的所有存储桶及其大小。但是当我 运行 脚本获取存储桶时,但是当 运行 获取大小的循环时,它会抛出错误。有人能指出我哪里出错了吗? bcos 当我 运行 单个存储桶的 awscli 命令时,它可以毫无问题地获取大小。 所需的输出将如下所示,但对于所有的桶,我已经获取了一个桶。 期望的输出:

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 }')

    #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 是单个字符串,而不是数组。