🍘

【AWS CLI】S3の空ディレクトも含めてコピー(CP)する方法

2025/02/18に公開

はじめに

aws s3 cpコマンドでコピーを行う際、空ディレクトリ[1]はコピーされません。
mvsyncでも同様です。

たとえば

SampleDirectory/
├─ Hoge/
│  └─ Fuga.pdf
└─ Piyo/

上記のディレクトリに対してaws s3 cpコマンドでコピーを実行すると、中身が空であるPiyoディレクトリはコピーされずに、下記の結果になります。

SampleDirectory/
└─ Hoge/
   └─ Fuga.pdf

そこで本記事では空ディレクトリも含めてコピーを行う方法を紹介します。

環境

aws-cli/2.9.21

空ディレクトリも含めてコピーする方法

  1. aws s3 lsコマンドでディレクトリ一覧を取得する。
aws s3 ls s3://sample-bucket/SampleDirectory/ --recursive | awk -F' ' '{print $NF}' | grep '/$' > ~/Desktop/folder-list.txt
  1. ディレクトリ一覧を元にディレクトリを作成する。
cat ~/Desktop/folder-list.txt | while read folder; do mkdir -p ~/Desktop/"$folder"; done
  1. 作成したディレクトリに対してコピーを実行する。
aws s3 cp s3://sample-bucket/SampleDirectory/ ~/Desktop/SampleDirectory/ --recursive

以上です。

脚注
  1. 厳密にはS3にディレクトリという概念はなく、オブジェクトキーに/を含めることでディレクトリ構造を表現している。 ↩︎

GitHubで編集を提案

Discussion