Rename objects atomically

Rename objects atomically within a bucket. To rename an object, you can use the Objects: move method.

Code sample

C#

For more information, see the Cloud Storage C# API reference documentation.

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


using Google.Cloud.Storage.V1;
using System;

public class MoveObjectSample
{
    /// <summary>
    /// Moves an object within a bucket with hierarchical namespace enabled.
    /// </summary>
    /// <param name="sourceBucketName">Name of the source bucket containing the object to move.</param>
    /// <param name="sourceObjectName">The name of the source object to move within the bucket.</param>
    /// <param name="destinationObjectName">The name of the new object to move to within the bucket.</param>
    public void MoveObject(
        string sourceBucketName = "source-bucket-name",
        string sourceObjectName = "source-object-name",
        string destinationObjectName = "destination-object-name")
    {
        var storage = StorageClient.Create();
        storage.MoveObject(sourceBucketName, sourceObjectName, destinationObjectName);
        Console.WriteLine($"Moved {sourceBucketName}/{sourceObjectName} to " + $"{sourceBucketName}/{destinationObjectName} within a hierarchical namespace enabled bucket.");
    }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-source-bucket';

// The ID of your GCS file
// const srcFileName = 'your-file-name';

// The new ID for your GCS file
// const destFileName = 'your-new-file-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function moveFileAtomic() {
  // Optional:
  // Set a generation-match precondition to avoid potential race conditions
  // and data corruptions. The request to copy 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.
  const moveOptions = {
    preconditionOpts: {
      ifGenerationMatch: destinationGenerationMatchPrecondition,
    },
  };

  // Moves the file automatically within the HNS enabled bucket
  await storage
    .bucket(bucketName)
    .file(srcFileName)
    .moveFileAtomic(destFileName, moveOptions);

  console.log(
    `gs://${bucketName}/${srcFileName} moved to gs://${bucketName}/${destFileName}`
  );
}

moveFileAtomic().catch(console.error);

PHP

For more information, see the Cloud Storage PHP API reference documentation.

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

use Google\Cloud\Storage\StorageClient;

/**
 * Move an object to a new name within HNS-enabled bucket.
 *
 * @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')
 * @param string $newObjectName the destination object name.
 *        (e.g. 'my-other-object')
 */
function move_object_atomic(string $bucketName, string $objectName, string $newObjectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->move($newObjectName);
    printf('Moved gs://%s/%s to gs://%s/%s' . PHP_EOL,
        $bucketName,
        $objectName,
        $bucketName,
        $newObjectName);
}

Python

For more information, see the Cloud Storage Python API reference documentation.

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

from google.cloud import storage


def move_object(bucket_name: str, blob_name: str, new_blob_name: str) -> None:
    """Moves a blob to a new name within the same bucket using the move API."""
    # The name of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The name of your GCS object to move
    # blob_name = "your-file-name"

    # The new name of the GCS object
    # new_blob_name = "new-file-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    blob_to_move = bucket.blob(blob_name)

    # Use move_blob to perform an efficient, server-side move.
    moved_blob = bucket.move_blob(
        blob=blob_to_move, new_name=new_blob_name
    )

    print(f"Blob {blob_to_move.name} has been moved to {moved_blob.name}.")

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

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

def move_object bucket_name:, source_file_name:, destination_file_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The name of your GCS object
  # source_file_name = "your-file-name"

  # The new object name which you want to craete
  # destination_file_name = "your-new-file-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name, skip_lookup: true

  bucket.move_file source_file_name, destination_file_name
  fetch_file = bucket.file destination_file_name
  puts "New File #{fetch_file.name} created\n"
end

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.