객체 나열하기

이 페이지는 Cloud Storage 버킷에 저장된 객체를 이름별 사전순으로 정리하여 나열하는 방법을 설명합니다.

시작하기 전에

객체를 나열하는 데 필요한 권한을 얻으려면 관리자에게 나열할 객체가 포함된 버킷에 대한 스토리지 객체 뷰어(roles/storage.objectViewer) IAM 역할을 부여해달라고 요청하세요. 관리형 폴더 내의 객체를 나열하려면 버킷 대신 보려는 객체가 포함된 관리형 폴더에 roles/storage.objectViewer를 부여하면 됩니다.

Google Cloud 콘솔을 사용하여 이 페이지의 태스크를 수행하려면 관리자에게 스토리지 객체 뷰어(roles/storage.objectViewer) 역할 외에도 뷰어(roles/viewer) 기본 역할을 부여해 달라고 요청하세요.

이러한 역할에는 객체를 나열하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 확장하세요.

필수 권한

  • storage.objects.list
  • storage.buckets.list
    • 이 권한은 Google Cloud 콘솔을 사용하여 이 페이지의 태스크를 수행하려는 경우에만 필요합니다.

다른 사전 정의된 역할이나 커스텀 역할을 사용하여 이러한 권한을 얻을 수도 있습니다.

버킷의 역할 부여에 대한 자세한 내용은 버킷에 IAM 사용을 참조하세요.

버킷의 객체 나열

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 콘텐츠를 볼 버킷의 이름을 클릭합니다.

명령줄

gcloud storage ls 명령어를 사용합니다.

gcloud storage ls gs://BUCKET_NAME

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 나열하려는 객체가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

다음 샘플은 버킷의 모든 객체를 나열합니다.

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name) {
  for (auto&& object_metadata : client.ListObjects(bucket_name)) {
    if (!object_metadata) throw std::move(object_metadata).status();

    std::cout << "bucket_name=" << object_metadata->bucket()
              << ", object_name=" << object_metadata->name() << "\n";
  }
}

다음 샘플은 지정된 프리픽스가 있는 객체를 나열합니다.

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& bucket_prefix) {
  for (auto&& object_metadata :
       client.ListObjects(bucket_name, gcs::Prefix(bucket_prefix))) {
    if (!object_metadata) throw std::move(object_metadata).status();

    std::cout << "bucket_name=" << object_metadata->bucket()
              << ", object_name=" << object_metadata->name() << "\n";
  }
}

C#

자세한 내용은 Cloud Storage C# API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

다음 샘플은 버킷의 모든 객체를 나열합니다.


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

public class ListFilesSample
{
    public IEnumerable<Google.Apis.Storage.v1.Data.Object> ListFiles(
        string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var storageObjects = storage.ListObjects(bucketName);
        Console.WriteLine($"Files in bucket {bucketName}:");
        foreach (var storageObject in storageObjects)
        {
            Console.WriteLine(storageObject.Name);
        }

        return storageObjects;
    }
}

다음 샘플은 지정된 프리픽스가 있는 객체를 나열합니다.


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

public class ListFilesWithPrefixSample
{
    /// <summary>
    /// Prefixes and delimiters can be used to emulate directory listings.
    /// Prefixes can be used to filter objects starting with prefix.
    /// The delimiter argument can be used to restrict the results to only the
    /// objects in the given "directory". Without the delimiter, the entire  tree
    /// under the prefix is returned.
    /// For example, given these objects:
    ///   a/1.txt
    ///   a/b/2.txt
    ///
    /// If you just specify prefix="a/", you'll get back:
    ///   a/1.txt
    ///   a/b/2.txt
    ///
    /// However, if you specify prefix="a/" and delimiter="/", you'll get back:
    ///   a/1.txt
    /// </summary>
    /// <param name="bucketName">The bucket to list the objects from.</param>
    /// <param name="prefix">The prefix to match. Only objects with names that start with this string will
    /// be returned. This parameter may be null or empty, in which case no filtering
    /// is performed.</param>
    /// <param name="delimiter">Used to list in "directory mode". Only objects whose names (aside from the prefix)
    /// do not contain the delimiter will be returned.</param>
    public IEnumerable<Google.Apis.Storage.v1.Data.Object> ListFilesWithPrefix(
        string bucketName = "your-unique-bucket-name",
        string prefix = "your-prefix",
        string delimiter = "your-delimiter")
    {
        var storage = StorageClient.Create();
        var options = new ListObjectsOptions { Delimiter = delimiter };
        var storageObjects = storage.ListObjects(bucketName, prefix, options);
        Console.WriteLine($"Objects in bucket {bucketName} with prefix {prefix}:");
        foreach (var storageObject in storageObjects)
        {
            Console.WriteLine(storageObject.Name);
        }
        return storageObjects;
    }
}

Go

자세한 내용은 Cloud Storage Go API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

다음 샘플은 버킷의 모든 객체를 나열합니다.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// listFiles lists objects within specified bucket.
func listFiles(w io.Writer, bucket string) error {
	// bucket := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	it := client.Bucket(bucket).Objects(ctx, nil)
	for {
		attrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Bucket(%q).Objects: %w", bucket, err)
		}
		fmt.Fprintln(w, attrs.Name)
	}
	return nil
}

다음 샘플은 지정된 프리픽스가 있는 객체를 나열합니다.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// listFilesWithPrefix lists objects using prefix and delimeter.
func listFilesWithPrefix(w io.Writer, bucket, prefix, delim string) error {
	// bucket := "bucket-name"
	// prefix := "/foo"
	// delim := "_"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	// Prefixes and delimiters can be used to emulate directory listings.
	// Prefixes can be used to filter objects starting with prefix.
	// The delimiter argument can be used to restrict the results to only the
	// objects in the given "directory". Without the delimiter, the entire tree
	// under the prefix is returned.
	//
	// For example, given these blobs:
	//   /a/1.txt
	//   /a/b/2.txt
	//
	// If you just specify prefix="a/", you'll get back:
	//   /a/1.txt
	//   /a/b/2.txt
	//
	// However, if you specify prefix="a/" and delim="/", you'll get back:
	//   /a/1.txt
	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	it := client.Bucket(bucket).Objects(ctx, &storage.Query{
		Prefix:    prefix,
		Delimiter: delim,
	})
	for {
		attrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Bucket(%q).Objects(): %w", bucket, err)
		}
		fmt.Fprintln(w, attrs.Name)
	}
	return nil
}

Java

자세한 내용은 Cloud Storage Java API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

다음 샘플은 버킷의 모든 객체를 나열합니다.

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListObjects {
  public static void listObjects(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Page<Blob> blobs = storage.list(bucketName);

    for (Blob blob : blobs.iterateAll()) {
      System.out.println(blob.getName());
    }
  }
}

다음 샘플은 지정된 프리픽스가 있는 객체를 나열합니다.

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListObjectsWithPrefix {
  public static void listObjectsWithPrefix(
      String projectId, String bucketName, String directoryPrefix) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The directory prefix to search for
    // String directoryPrefix = "myDirectory/"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    /**
     * Using the Storage.BlobListOption.currentDirectory() option here causes the results to display
     * in a "directory-like" mode, showing what objects are in the directory you've specified, as
     * well as what other directories exist in that directory. For example, given these blobs:
     *
     * <p>a/1.txt a/b/2.txt a/b/3.txt
     *
     * <p>If you specify prefix = "a/" and don't use Storage.BlobListOption.currentDirectory(),
     * you'll get back:
     *
     * <p>a/1.txt a/b/2.txt a/b/3.txt
     *
     * <p>However, if you specify prefix = "a/" and do use
     * Storage.BlobListOption.currentDirectory(), you'll get back:
     *
     * <p>a/1.txt a/b/
     *
     * <p>Because a/1.txt is the only file in the a/ directory and a/b/ is a directory inside the
     * /a/ directory.
     */
    Page<Blob> blobs =
        storage.list(
            bucketName,
            Storage.BlobListOption.prefix(directoryPrefix),
            Storage.BlobListOption.currentDirectory());

    for (Blob blob : blobs.iterateAll()) {
      System.out.println(blob.getName());
    }
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

다음 샘플은 버킷의 모든 객체를 나열합니다.

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

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

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

async function listFiles() {
  // Lists files in the bucket
  const [files] = await storage.bucket(bucketName).getFiles();

  console.log('Files:');
  files.forEach(file => {
    console.log(file.name);
  });
}

listFiles().catch(console.error);

다음 샘플은 지정된 프리픽스가 있는 객체를 나열합니다.

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

// The directory prefix to search for
// const prefix = 'myDirectory/';

// The delimiter to use
// const delimiter = '/';

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

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

async function listFilesByPrefix() {
  /**
   * This can be used to list all blobs in a "folder", e.g. "public/".
   *
   * The delimiter argument can be used to restrict the results to only the
   * "files" in the given "folder". Without the delimiter, the entire tree under
   * the prefix is returned. For example, given these blobs:
   *
   *   /a/1.txt
   *   /a/b/2.txt
   *
   * If you just specify prefix = 'a/', you'll get back:
   *
   *   /a/1.txt
   *   /a/b/2.txt
   *
   * However, if you specify prefix='a/' and delimiter='/', you'll get back:
   *
   *   /a/1.txt
   */
  const options = {
    prefix: prefix,
  };

  if (delimiter) {
    options.delimiter = delimiter;
  }

  // Lists files in the bucket, filtered by a prefix
  const [files] = await storage.bucket(bucketName).getFiles(options);

  console.log('Files:');
  files.forEach(file => {
    console.log(file.name);
  });
}

listFilesByPrefix().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

다음 샘플은 버킷의 모든 객체를 나열합니다.

use Google\Cloud\Storage\StorageClient;

/**
 * List Cloud Storage bucket objects.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function list_objects(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    foreach ($bucket->objects() as $object) {
        printf('Object: %s' . PHP_EOL, $object->name());
    }
}

다음 샘플은 지정된 프리픽스가 있는 객체를 나열합니다.

use Google\Cloud\Storage\StorageClient;

/**
 * List Cloud Storage bucket objects with specified prefix.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $directoryPrefix the prefix to use in the list objects API call.
 *        (e.g. 'myDirectory/')
 */
function list_objects_with_prefix(string $bucketName, string $directoryPrefix): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $options = ['prefix' => $directoryPrefix];
    foreach ($bucket->objects($options) as $object) {
        printf('Object: %s' . PHP_EOL, $object->name());
    }
}

Python

자세한 내용은 Cloud Storage Python API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

다음 샘플은 버킷의 모든 객체를 나열합니다.

from google.cloud import storage


def list_blobs(bucket_name):
    """Lists all the blobs in the bucket."""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()

    # Note: Client.list_blobs requires at least package version 1.17.0.
    blobs = storage_client.list_blobs(bucket_name)

    # Note: The call returns a response only when the iterator is consumed.
    for blob in blobs:
        print(blob.name)

다음 샘플은 지정된 프리픽스가 있는 객체를 나열합니다.

from google.cloud import storage


def list_blobs_with_prefix(bucket_name, prefix, delimiter=None):
    """Lists all the blobs in the bucket that begin with the prefix.

    This can be used to list all blobs in a "folder", e.g. "public/".

    The delimiter argument can be used to restrict the results to only the
    "files" in the given "folder". Without the delimiter, the entire tree under
    the prefix is returned. For example, given these blobs:

        a/1.txt
        a/b/2.txt

    If you specify prefix ='a/', without a delimiter, you'll get back:

        a/1.txt
        a/b/2.txt

    However, if you specify prefix='a/' and delimiter='/', you'll get back
    only the file directly under 'a/':

        a/1.txt

    As part of the response, you'll also get back a blobs.prefixes entity
    that lists the "subfolders" under `a/`:

        a/b/


    Note: If you only want to list prefixes a/b/ and don't want to iterate over
    blobs, you can do

    ```
    for page in blobs.pages:
        print(page.prefixes)
    ```
    """

    storage_client = storage.Client()

    # Note: Client.list_blobs requires at least package version 1.17.0.
    blobs = storage_client.list_blobs(
        bucket_name, prefix=prefix, delimiter=delimiter
    )

    # Note: The call returns a response only when the iterator is consumed.
    print("Blobs:")
    for blob in blobs:
        print(blob.name)

    if delimiter:
        print("Prefixes:")
        for prefix in blobs.prefixes:
            print(prefix)

Ruby

자세한 내용은 Cloud Storage Ruby API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

다음 샘플은 버킷의 모든 객체를 나열합니다.

def list_files bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.files.each do |file|
    puts file.name
  end
end

다음 샘플은 지정된 프리픽스가 있는 객체를 나열합니다.

def list_files_with_prefix bucket_name:, prefix:, delimiter: nil
  # Lists all the files in the bucket that begin with the prefix.
  #
  # This can be used to list all files in a "folder", e.g. "public/".
  #
  # The delimiter argument can be used to restrict the results to only the
  # "files" in the given "folder". Without the delimiter, the entire tree under
  # the prefix is returned. For example, given these files:
  #
  #     a/1.txt
  #     a/b/2.txt
  #
  # If you just specify `prefix: "a"`, you will get back:
  #
  #     a/1.txt
  #     a/b/2.txt
  #
  # However, if you specify `prefix: "a"` and `delimiter: "/"`, you will get back:
  #
  #     a/1.txt

  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The directory prefix to search for
  # prefix = "a"

  # The delimiter to be used to restrict the results
  # delimiter = "/"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name
  files   = bucket.files prefix: prefix, delimiter: delimiter

  files.each do |file|
    puts file.name
  end
end

REST API

JSON API

  1. Authorization 헤더에 대한 액세스 토큰을 생성하려면 gcloud CLI가 설치 및 초기화되어 있어야 합니다.

  2. cURL을 사용해서 객체 나열 요청을 포함하여 JSON API를 호출합니다.

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

    여기서 BUCKET_NAME은 객체를 나열할 버킷의 이름입니다. 예를 들면 my-bucket입니다.

XML API

  1. Authorization 헤더에 대한 액세스 토큰을 생성하려면 gcloud CLI가 설치 및 초기화되어 있어야 합니다.

  2. cURL을 사용해서 GET 버킷 요청을 포함하여 XML API를 호출합니다.

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?list-type=2"

    여기서 BUCKET_NAME은 객체를 나열할 버킷의 이름입니다. 예를 들면 my-bucket입니다.

    prefix=PREFIX 쿼리 문자열 파라미터를 사용하여 결과를 지정된 프리픽스가 있는 객체로 제한할 수 있습니다.

폴더의 객체 나열

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 폴더가 포함된 버킷의 이름을 클릭합니다.

  3. 버킷 세부정보 페이지의 객체 탭에서 콘텐츠를 볼 폴더의 이름을 클릭합니다.

명령줄

gcloud storage ls 명령어를 사용하여 폴더의 객체를 나열합니다.

gcloud storage ls gs://BUCKET_NAME/FOLDER_NAME

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 폴더가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.

  • FOLDER_NAME은 나열하려는 객체가 포함된 폴더의 이름입니다. 예를 들면 my-folder입니다.

REST API

JSON API

폴더의 객체를 나열하려면 prefixdelimiter 파라미터와 함께 객체 나열 요청을 사용합니다. prefix 파라미터가 설정되면 목록 작업의 범위가 프리픽스 아래의 객체와 폴더만 반환하도록 지정됩니다. delimiter 파라미터가 설정되면 응답의 prefixes[] 목록이 지정된 프리픽스 아래의 폴더 이름으로 채워집니다.

예를 들면 다음과 같습니다.

  • my-bucket 버킷 내의 image/ 폴더에 있는 모든 객체를 나열하려면 "https://storage.googleapis.com/storage/v1/b/my-bucket/o?prefix=image&delimiter=/" URL을 사용합니다.

    그러면 my-bucket/image/cat.jpegmy-bucket/image/dog.jpeg 객체가 반환될 수 있습니다.

  • image/ 내의 하위 폴더에 객체를 포함하려면 delimiter 파라미터 "https://storage.googleapis.com/storage/v1/b/my-bucket/o?prefix=image"를 삭제합니다.

    my-bucket/image/cat.jpeg, my-bucket/image/dog.jpeg, my-bucket/image/dog/shiba.jpeg 객체가 반환될 수 있습니다.

객체 나열 요청에서 와일드 카드를 사용하고 glob 표현식으로 객체를 일치시키려면 matchGlob 파라미터를 사용합니다. 예를 들어 matchGlob=**.jpeg.jpeg로 끝나는 모든 객체와 일치합니다. matchGlob를 사용하는 경우 delimiter/로 설정해야 합니다.

예를 들어 다음 URL을 사용하여 image 폴더 내에서 .jpeg로 끝나는 모든 객체를 일치시킵니다. "https://storage.googleapis.com/storage/v1/b/my-bucket/o?prefix=image&delimiter=/&matchGlob=**.jpeg"

파라미터를 사용하여 객체를 필터링하는 방법에 대한 자세한 내용은 객체 나열 JSON API 참고 문서를 참고하세요.

사용 사례

prefix를 사용하여 폴더의 콘텐츠를 나열하는 것은 폴더의 객체를 나열할 수 있는 권한만 있는 경우에 유용하지만 전체 버킷에는 그렇지 않습니다. 예를 들어 관리형 폴더 my-bucket/my-managed-folder-b/에 대한 스토리지 객체 뷰어(roles/storage.objectViewer) IAM 역할이 있지만 관리형 폴더 my-bucket/my-managed-folder-a/에는 없다고 가정해 보겠습니다. my-managed-folder-a의 객체만 반환하려면 prefix=my-managed-folder-a/를 지정하면 됩니다.

객체 필터링

객체를 나열할 때 목록 요청에서 프리픽스 또는 서픽스를 사용하여 이름별로 객체를 필터링할 수 있습니다.

콘솔

버킷 또는 폴더의 객체를 필터링하고 정렬하는 방법은 필터링 및 정렬을 참고하세요.

명령줄

gcloud storage ls 명령어에서 와일드 카드를 사용하여 객체를 프리픽스 또는 서픽스로 필터링할 수 있습니다. 예를 들어 다음 명령어는 이름이 image로 시작하고 .png로 끝나는 my-bucket 버킷의 객체만 나열합니다.

gcloud storage ls gs://my-bucket/image*.png

요청이 성공하면 응답은 다음과 비슷합니다.

gs://my-bucket/image.png
gs://my-bucket/image-dog.png
gs://my-bucket/image-cat.png
...

경로에서 0개 이상의 폴더 수준을 일치시키려면 이중 별표 와일드 카드를 사용하면 됩니다. 예를 들어 다음 명령어는 버킷 my-bucket 내의 폴더 또는 하위 폴더에서 이름이 .jpeg로 끝나는 객체만 나열합니다.

gcloud storage ls gs://my-bucket/**/*.jpeg

요청이 성공하면 응답은 다음과 비슷합니다.

gs://my-bucket/puppy.jpeg
gs://my-bucket/pug.jpeg
gs://my-bucket/pets/dog.jpeg
...

REST API

폴더 또는 객체 이름 프리픽스로 객체를 필터링하는 방법은 폴더의 객체 나열을 참고하세요.

객체 나열 시 성능 고려사항

계층적 네임스페이스가 사용 설정된 버킷의 기본 구조는 평면적 네임스페이스 버킷과 비교할 때 객체 나열 작업의 성능에 영향을 줄 수 있습니다. 자세한 내용은 계층적 네임스페이스가 사용 설정된 버킷에서 성 능 최적화를 참고하세요.

다음 단계