Delete objects

This page shows you how to deleteobjects from your buckets inCloud Storage.

Caution: By default, Cloud Storage retains soft-deleted objectsfor a duration of seven days. If you have accidentally deleted the objects, youcan restore these soft-deleted objects during this duration. However, if youhave disabledsoft delete for your bucket, you cannot recoverdeleted objects. For more information on how to prevent accidental datadeletion, seeOptions for controlling data lifecycles.

Required roles

To get the permissions that you need to delete objects, ask your administratorto grant you the Storage Object User (roles/storage.objectUser)IAM role for the bucket that contains the objects you want todelete.

If you plan on using the Google Cloud console to complete the tasks on thispage, ask your administrator to grant you the Storage Admin(roles/storage.admin) role instead of the Storage Object User(roles/storage.objectUser) role, or the Viewer (roles/viewer) basic rolein addition to the Storage Object User (roles/storage.objectUser) role.

These roles contain the permissions required to delete objects. To see theexact permissions that are required, expand theRequired permissionssection:

Required permissions

  • storage.objects.delete
  • storage.objects.list
    • This permission is only needed when using the Google Cloud console, orwhen using the--recursive flag or wildcards inGoogle Cloud CLI.
  • storage.buckets.list
    • This permission is only needed when using the Google Cloud console toperform the instructions on this page.

You can also get these permissions with otherpredefined roles orcustom roles.

For information about granting roles on buckets, seeSet and manage IAM policies on buckets.

Delete an object

Note: Deleting data might incurearly deletion charges if the data wasoriginally stored as Nearline storage, Coldline storage, orArchive storage. Also note that if you have enabledObject Versioningfor your bucket, the original object remains in your bucket until it isexplicitly deleted using itsgeneration number.

Complete the following steps to delete objects from one of yourCloud Storage buckets:

Console

  1. In the Google Cloud console, go to the Cloud StorageBuckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket that containsthe objects you want to delete.

    TheBucket details page opens, with theObjects tab selected.

  3. Navigate to the objects, which may be located in a folder.

  4. Click the checkbox for each object you want to delete.

    You can also click the checkbox for folders, which will delete allobjects contained in that folder.

  5. Click theDelete button.

  6. ClickDelete in the dialog that appears.

If you delete many objects at once, you can track deletion progress byclicking theNotifications icon in the Google Cloud console. TheGoogle Cloud console can bulk delete up to several million objectsand does so in the background.

To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, seeTroubleshooting.

Command line

Use theGoogle Cloud CLI commandgcloud storage rm:

gcloud storage rm gs://BUCKET_NAME/OBJECT_NAME

Where:

  • BUCKET_NAME is the name of the bucket containingthe object you want to delete. For example,my-bucket.
  • OBJECT_NAME is the name of the object you wantto delete. For example,pets/dog.png.

If successful, the response is similar to the following example:

Removing objects:Removing gs://example-bucket/file.txt...  Completed 1/1
Note: You can delete groups of objects that have the same prefix, such asobjects whose namesmimic a folder structure, by using the--recursive flag. For example:gcloud storage rm --recursive gs://my-bucket/dir/

Client libraries

C++

For more information, see theCloud StorageC++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

namespacegcs=::google::cloud::storage;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name){google::cloud::Statusstatus=client.DeleteObject(bucket_name,object_name);if(!status.ok())throwstd::runtime_error(status.message());std::cout <<"Deleted " <<object_name <<" in bucket " <<bucket_name            <<"\n";}

C#

For more information, see theCloud StorageC# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

usingGoogle.Cloud.Storage.V1;usingSystem;publicclassDeleteFileSample{publicvoidDeleteFile(stringbucketName="your-unique-bucket-name",stringobjectName="your-object-name"){varstorage=StorageClient.Create();storage.DeleteObject(bucketName,objectName);Console.WriteLine($"Deleted {objectName}.");}}

Go

For more information, see theCloud StorageGo API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

import("context""fmt""io""time""cloud.google.com/go/storage")// deleteFile removes specified object.funcdeleteFile(wio.Writer,bucket,objectstring)error{// bucket := "bucket-name"// object := "object-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()o:=client.Bucket(bucket).Object(object)// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request to delete the file is aborted// if the object's generation number does not match your precondition.attrs,err:=o.Attrs(ctx)iferr!=nil{returnfmt.Errorf("object.Attrs: %w",err)}o=o.If(storage.Conditions{GenerationMatch:attrs.Generation})iferr:=o.Delete(ctx);err!=nil{returnfmt.Errorf("Object(%q).Delete: %w",object,err)}fmt.Fprintf(w,"Blob %v deleted.\n",object)returnnil}

Java

For more information, see theCloud StorageJava API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassDeleteObject{publicstaticvoiddeleteObject(StringprojectId,StringbucketName,StringobjectName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The ID of your GCS object// String objectName = "your-object-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Blobblob=storage.get(bucketName,objectName);if(blob==null){System.out.println("The object "+objectName+" wasn't found in "+bucketName);return;}BlobIdidWithGeneration=blob.getBlobId();// Deletes the blob specified by its id. When the generation is present and non-null it will be// specified in the request.// If versioning is enabled on the bucket and the generation is present in the delete request,// only the version of the object with the matching generation will be deleted.// If instead you want to delete the current version, the generation should be dropped by// performing the following.// BlobId idWithoutGeneration =//    BlobId.of(idWithGeneration.getBucket(), idWithGeneration.getName());// storage.delete(idWithoutGeneration);storage.delete(idWithGeneration);System.out.println("Object "+objectName+" was permanently deleted from "+bucketName);}}

Node.js

For more information, see theCloud StorageNode.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of your GCS file// const fileName = 'your-file-name';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();// Optional:// Set a generation-match precondition to avoid potential race conditions// and data corruptions. The request to delete is aborted if the object's// generation number does not match your precondition. For a destination// object that does not yet exist, set the ifGenerationMatch precondition to 0// If the destination object already exists in your bucket, set instead a// generation-match precondition using its generation number.constdeleteOptions={ifGenerationMatch:generationMatchPrecondition,};asyncfunctiondeleteFile(){awaitstorage.bucket(bucketName).file(fileName).delete(deleteOptions);console.log(`gs://${bucketName}/${fileName} deleted`);}deleteFile().catch(console.error);

PHP

For more information, see theCloud StoragePHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

use Google\Cloud\Storage\StorageClient;/** * Delete an object. * * @param string $bucketName The name of your Cloud Storage bucket. *        (e.g. 'my-bucket') * @param string $objectName The name of your Cloud Storage object. *        (e.g. 'my-object') */function delete_object(string $bucketName, string $objectName): void{    $storage = new StorageClient();    $bucket = $storage->bucket($bucketName);    $object = $bucket->object($objectName);    $object->delete();    printf('Deleted gs://%s/%s' . PHP_EOL, $bucketName, $objectName);}

Python

For more information, see theCloud StoragePython API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

fromgoogle.cloudimportstoragedefdelete_blob(bucket_name,blob_name):"""Deletes a blob from the bucket."""# bucket_name = "your-bucket-name"# blob_name = "your-object-name"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)blob=bucket.blob(blob_name)generation_match_precondition=None# Optional: set a generation-match precondition to avoid potential race conditions# and data corruptions. The request to delete is aborted if the object's# generation number does not match your precondition.blob.reload()# Fetch blob metadata to use in generation_match_precondition.generation_match_precondition=blob.generationblob.delete(if_generation_match=generation_match_precondition)print(f"Blob{blob_name} deleted.")

Ruby

For more information, see theCloud StorageRuby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

defdelete_filebucket_name:,file_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of your GCS object# file_name = "your-file-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_name,skip_lookup:truefile=bucket.filefile_namefile.deleteputs"Deleted#{file.name}"end

REST APIs

JSON API

Note: Each deletion request sent to the JSON API can contain only asingle object to delete.
  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. UsecURL to call theJSON API with aDELETErequest:

    curl -X DELETE \  -H "Authorization: Bearer $(gcloud auth print-access-token)" \  "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME"

    Where:

    • BUCKET_NAME is the name of the bucketcontaining the object you want to delete. For example,my-bucket.
    • OBJECT_NAME is the URL-encoded name ofthe object you want to delete. For example,pets/dog.png,URL-encoded aspets%2Fdog.png.

XML API

Note: Each deletion request sent to the XML API can contain only asingle object to delete.
  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. UsecURL to call theXML API with aDELETE Object request:

    curl -X DELETE \  -H "Authorization: Bearer $(gcloud auth print-access-token)" \  "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    Where:

    • BUCKET_NAME is the name of the bucketcontaining the object you want to delete. For example,my-bucket.
    • OBJECT_NAME is the URL-encoded name ofthe object you want to delete. For example,pets/dog.png,URL-encoded aspets%2Fdog.png.

Delete objects in bulk

If you want to bulk delete a hundred thousand or more objects, avoid usinggcloud storage, as the process takes a long time to complete.Instead, consider one of the following options:

  • TheObject Lifecycle Management feature can delete any number of objects.To bulk delete objects in your bucket using this feature,set a lifecycle configuration rule on your bucket where the conditionhasAge set to 0 days and the action is set todelete. Once you set therule, Cloud Storageperforms the bulk delete asynchronously.

  • The Google Cloud console is also a recommended option when deleting up to onemillion objects. Once you initiate such a deletion request, the processoccurs in the background. You can check the status of your bulk deletion byclicking theNotifications button()in the Google Cloud console header.

  • When using certain client libraries or when using the JSON API directly, youcanbatch your deletion requests to reduce the number of HTTPconnections you need to make.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.