Use DeleteBucket with an Amazon SDK or CLI - Amazon Simple Storage Service
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Use DeleteBucket with an Amazon SDK or CLI

The following code examples show how to use DeleteBucket.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example:

.NET
Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// <summary> /// Shows how to delete an Amazon S3 bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the Amazon S3 bucket to delete.</param> /// <returns>A boolean value that represents the success or failure of /// the delete operation.</returns> public static async Task<bool> DeleteBucketAsync(IAmazonS3 client, string bucketName) { var request = new DeleteBucketRequest { BucketName = bucketName, }; var response = await client.DeleteBucketAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • For API details, see DeleteBucket in Amazon SDK for .NET API Reference.

Bash
Amazon CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function delete_bucket # # This function deletes the specified bucket. # # Parameters: # $1 - The name of the bucket. # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function delete_bucket() { local bucket_name=$1 local response response=$(aws s3api delete-bucket \ --bucket "$bucket_name") # shellcheck disable=SC2181 if [[ $? -ne 0 ]]; then errecho "ERROR: AWS reports s3api delete-bucket failed.\n$response" return 1 fi }
  • For API details, see DeleteBucket in Amazon CLI Command Reference.

C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

bool AwsDoc::S3::DeleteBucket(const Aws::String &bucketName, const Aws::Client::ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); Aws::S3::Model::DeleteBucketRequest request; request.SetBucket(bucketName); Aws::S3::Model::DeleteBucketOutcome outcome = client.DeleteBucket(request); if (!outcome.IsSuccess()) { const Aws::S3::S3Error &err = outcome.GetError(); std::cerr << "Error: DeleteBucket: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { std::cout << "The bucket was deleted" << std::endl; } return outcome.IsSuccess(); }
  • For API details, see DeleteBucket in Amazon SDK for C++ API Reference.

CLI
Amazon CLI

The following command deletes a bucket named my-bucket:

aws s3api delete-bucket --bucket my-bucket --region us-east-1
  • For API details, see DeleteBucket in Amazon CLI Command Reference.

Go
SDK for Go V2
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// BucketBasics encapsulates the Amazon Simple Storage Service (Amazon S3) actions // used in the examples. // It contains S3Client, an Amazon S3 service client that is used to perform bucket // and object actions. type BucketBasics struct { S3Client *s3.Client } // DeleteBucket deletes a bucket. The bucket must be empty or an error is returned. func (basics BucketBasics) DeleteBucket(bucketName string) error { _, err := basics.S3Client.DeleteBucket(context.TODO(), &s3.DeleteBucketInput{ Bucket: aws.String(bucketName)}) if err != nil { log.Printf("Couldn't delete bucket %v. Here's why: %v\n", bucketName, err) } return err }
  • For API details, see DeleteBucket in Amazon SDK for Go API Reference.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() .bucket(bucket) .build(); s3.deleteBucket(deleteBucketRequest); s3.close();
  • For API details, see DeleteBucket in Amazon SDK for Java 2.x API Reference.

JavaScript
SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Delete the bucket.

import { DeleteBucketCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); // Delete a bucket. export const main = async () => { const command = new DeleteBucketCommand({ Bucket: "test-bucket", }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };
PHP
SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Delete an empty bucket.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $this->s3client->deleteBucket([ 'Bucket' => $this->bucketName, ]); echo "Deleted bucket $this->bucketName.\n"; } catch (Exception $exception) { echo "Failed to delete $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with bucket deletion before continuing."); }
  • For API details, see DeleteBucket in Amazon SDK for PHP API Reference.

PowerShell
Tools for PowerShell

Example 1: This command removes all objects and object versions from the bucket 'test-files' and then deletes the bucket. The command will prompt for confirmation before proceeding. Add the -Force switch to suppress confirmation. Note that buckets that are not empty cannot be deleted.

Remove-S3Bucket -BucketName test-files -DeleteBucketContent
  • For API details, see DeleteBucket in Amazon Tools for PowerShell Cmdlet Reference.

Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

class BucketWrapper: """Encapsulates S3 bucket actions.""" def __init__(self, bucket): """ :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3 that wraps bucket actions in a class-like structure. """ self.bucket = bucket self.name = bucket.name def delete(self): """ Delete the bucket. The bucket must be empty or an error is raised. """ try: self.bucket.delete() self.bucket.wait_until_not_exists() logger.info("Bucket %s successfully deleted.", self.bucket.name) except ClientError: logger.exception("Couldn't delete bucket %s.", self.bucket.name) raise
  • For API details, see DeleteBucket in Amazon SDK for Python (Boto3) API Reference.

Ruby
SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

# Deletes the objects in an Amazon S3 bucket and deletes the bucket. # # @param bucket [Aws::S3::Bucket] The bucket to empty and delete. def delete_bucket(bucket) puts("\nDo you want to delete all of the objects as well as the bucket (y/n)? ") answer = gets.chomp.downcase if answer == "y" bucket.objects.batch_delete! bucket.delete puts("Emptied and deleted bucket #{bucket.name}.\n") end rescue Aws::Errors::ServiceError => e puts("Couldn't empty and delete bucket #{bucket.name}.") puts("\t#{e.code}: #{e.message}") raise end
  • For API details, see DeleteBucket in Amazon SDK for Ruby API Reference.

Rust
SDK for Rust
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

pub async fn delete_bucket(client: &Client, bucket_name: &str) -> Result<(), Error> { client.delete_bucket().bucket(bucket_name).send().await?; println!("Bucket deleted"); Ok(()) }
  • For API details, see DeleteBucket in Amazon SDK for Rust API reference.

SAP ABAP
SDK for SAP ABAP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

TRY. lo_s3->deletebucket( iv_bucket = iv_bucket_name ). MESSAGE 'Deleted S3 bucket.' TYPE 'I'. CATCH /aws1/cx_s3_nosuchbucket. MESSAGE 'Bucket does not exist.' TYPE 'E'. ENDTRY.
  • For API details, see DeleteBucket in Amazon SDK for SAP ABAP API reference.

Swift
SDK for Swift
Note

This is prerelease documentation for an SDK in preview release. It is subject to change.

Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

public func deleteBucket(name: String) async throws { let input = DeleteBucketInput( bucket: name ) _ = try await client.deleteBucket(input: input) }
  • For API details, see DeleteBucket in Amazon SDK for Swift API reference.

For a complete list of Amazon SDK developer guides and code examples, see Using this service with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.