文件範例儲存庫中有更多 AWS SDK可用的範例。 AWS SDK
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
DeleteBucket
搭配 AWS SDK或 使用 CLI
下列程式碼範例示範如何使用 DeleteBucket
。
動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:
- .NET
-
- AWS SDK for .NET
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /// <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; }
-
如需API詳細資訊,請參閱 參考 DeleteBucket中的 。 AWS SDK for .NET API
-
- Bash
-
- AWS CLI 使用 Bash 指令碼
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 ############################################################################### # 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 }
-
如需API詳細資訊,請參閱 命令參考 DeleteBucket中的 。 AWS CLI
-
- C++
-
- SDK 適用於 C++
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 bool AwsDoc::S3::deleteBucket(const Aws::String &bucketName, const Aws::S3::S3ClientConfiguration &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(); }
-
如需API詳細資訊,請參閱 參考 DeleteBucket中的 。 AWS SDK for C++ API
-
- CLI
-
- AWS CLI
-
下列命令會刪除名為 的儲存貯體
my-bucket
:aws s3api delete-bucket --bucket
my-bucket
--regionus-east-1
-
如需API詳細資訊,請參閱 命令參考 DeleteBucket
中的 。 AWS CLI
-
- Go
-
- SDK for Go V2
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 // 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(ctx context.Context, bucketName string) error { _, err := basics.S3Client.DeleteBucket(ctx, &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 }
-
如需API詳細資訊,請參閱 參考 DeleteBucket
中的 。 AWS SDK for Go API
-
- Java
-
- SDK 適用於 Java 2.x
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /** * Deletes an S3 bucket asynchronously. * * @param bucket the name of the bucket to be deleted * @return a {@link CompletableFuture} that completes when the bucket deletion is successful, or throws a {@link RuntimeException} * if an error occurs during the deletion process */ public CompletableFuture<Void> deleteBucketAsync(String bucket) { DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() .bucket(bucket) .build(); CompletableFuture<DeleteBucketResponse> response = getAsyncClient().deleteBucket(deleteBucketRequest); response.whenComplete((deleteRes, ex) -> { if (deleteRes != null) { logger.info(bucket + " was deleted."); } else { throw new RuntimeException("An S3 exception occurred during bucket deletion", ex); } }); return response.thenApply(r -> null); }
-
如需API詳細資訊,請參閱 參考 DeleteBucket中的 。 AWS SDK for Java 2.x API
-
- JavaScript
-
- SDK 適用於 JavaScript (v3)
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 刪除儲存貯體。
import { DeleteBucketCommand, S3Client, S3ServiceException, } from "@aws-sdk/client-s3"; /** * Delete an Amazon S3 bucket. * @param {{ bucketName: string }} */ export const main = async ({ bucketName }) => { const client = new S3Client({}); const command = new DeleteBucketCommand({ Bucket: bucketName, }); try { await client.send(command); console.log("Bucket was deleted."); } catch (caught) { if ( caught instanceof S3ServiceException && caught.name === "NoSuchBucket" ) { console.error( `Error from S3 while deleting bucket. The bucket doesn't exist.`, ); } else if (caught instanceof S3ServiceException) { console.error( `Error from S3 while deleting the bucket. ${caught.name}: ${caught.message}`, ); } else { throw caught; } } };
-
如需詳細資訊,請參閱《AWS SDK for JavaScript 開發人員指南》。
-
如需API詳細資訊,請參閱 參考 DeleteBucket中的 。 AWS SDK for JavaScript API
-
- PHP
-
- 適用於 PHP 的 SDK
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 刪除空的儲存貯體。
$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."); }
-
如需API詳細資訊,請參閱 參考 DeleteBucket中的 。 AWS SDK for PHP API
-
- PowerShell
-
- 適用於 的工具 PowerShell
-
範例 1:此命令會從儲存貯體 'test-files' 中移除所有物件和物件版本,然後刪除儲存貯體。繼續之前,命令會提示您進行確認。新增 -Force 切換以隱藏確認。請注意,無法刪除不是空的儲存貯體。
Remove-S3Bucket -BucketName amzn-s3-demo-bucket -DeleteBucketContent
-
如需API詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考 DeleteBucket中的 。
-
- Python
-
- SDK for Python (Boto3)
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 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
-
如需API詳細資訊,請參閱 DeleteBucket 中的 AWS SDK for Python (Boto3) API參考 。
-
- Ruby
-
- SDK 適用於 Ruby
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 # 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
-
如需API詳細資訊,請參閱 參考 DeleteBucket中的 。 AWS SDK for Ruby API
-
- Rust
-
- SDK for Rust
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 pub async fn delete_bucket( client: &aws_sdk_s3::Client, bucket_name: &str, ) -> Result<(), S3ExampleError> { let resp = client.delete_bucket().bucket(bucket_name).send().await; match resp { Ok(_) => Ok(()), Err(err) => { if err .as_service_error() .and_then(aws_sdk_s3::error::ProvideErrorMetadata::code) == Some("NoSuchBucket") { Ok(()) } else { Err(S3ExampleError::from(err)) } } } }
-
如需API詳細資訊,請參閱 DeleteBucket
中的 AWS SDK for Rust API參考 。
-
- SAP ABAP
-
- SDK 適用於 SAP ABAP
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 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.
-
如需API詳細資訊,請參閱DeleteBucket中的 AWS SDK 以取得SAPABAPAPI參考 。
-
- Swift
-
- SDK 適用於 Swift
-
注意
還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 import AWSS3 public func deleteBucket(name: String) async throws { let input = DeleteBucketInput( bucket: name ) do { _ = try await client.deleteBucket(input: input) } catch { print("ERROR: ", dump(error, name: "Deleting a bucket")) throw error } }
-
如需API詳細資訊,請參閱DeleteBucket
中的 AWS SDK 中的 Swift API參考。
-