AWS S3: How to delete all contents of a directory in a bucket but not the directory itself?

Viewed 15560

I have an AWS S3 bucket entitled static.mysite.com

This bucket contains a directory called html

I want to use the AWS Command Line Interface to remove all contents of the html directory, but not the directory itself. How can I do it?

This command deletes the directory too:

aws s3 rm s3://static.mysite.com/html/ --recursive

I don't see the answer to this question in the manual entry for AWS S3 rm.

3 Answers

Old question, but I didn't see the answer here. If you have a use case to keep the 'folder' prefix, but delete all the files, you can use --exclude with an empty match string. I found the --exclude "." and --exclude ".." options do not prevent the folder from being deleted. Use this:

aws s3 rm s3://static.mysite.com/html/ --recursive --exclude ""

I just want to confirm how the folders were created...

If you created the "subA" folder manually and then deleted the suba1 folder, you should find that the the "subA" folder remains. When you create a folder manually, you are actually creating a folder "object" which is similar to any other file/object that you upload to S3.

However, if a file was uploaded directly to a location in S3 (when the "subA" and "suba1" folder don't exist yet) you'll find that the "subA" and "suba1" folders are created automatically. You can do this using something like the AWS CLI tool e.g:

aws s3 cp file1.txt s3://bucket/subA/suba1/file1.txt

If you now delete file1.txt, there will no longer be any objects within the "subA" folder and you'll find that the "subA" and "suba1" folders no longer exist.

If another file (file2.txt) was uploaded to the path "bucket/subA/file2.txt", and you deleted file1.txt (from the previous example) you'll find that the "subA" folder remains and the "suba1" folder disappears.

https://forums.aws.amazon.com/thread.jspa?threadID=219733

aws s3 rm s3://static.mysite.com/html/ --recursive --exclude ""

this command worked for me to delete all the files but not the folder.

Related