0
0
GcpHow-ToBeginner · 4 min read

How to Use gsutil Command in GCP: Syntax, Examples, and Tips

Use the gsutil command-line tool to manage Google Cloud Storage resources by running commands like gsutil cp to copy files. Install the Google Cloud SDK, then open your terminal and run gsutil commands to upload, download, or list storage buckets and objects.
📐

Syntax

The basic syntax of the gsutil command is:

  • gsutil [command] [options] [arguments]

Here:

  • command: The action to perform, like cp (copy), ls (list), or rm (remove).
  • options: Optional flags to modify the command behavior, such as -r for recursive operations.
  • arguments: The source and destination paths, which can be local files or Cloud Storage URLs starting with gs://.
bash
gsutil [command] [options] [arguments]
💻

Example

This example shows how to upload a local file to a Cloud Storage bucket and then list the contents of that bucket.

bash
gsutil cp ./localfile.txt gs://my-bucket/
gsutil ls gs://my-bucket/
Output
Copying file://./localfile.txt [Content-Type=text/plain]... /gs://my-bucket/localfile.txt
⚠️

Common Pitfalls

Common mistakes when using gsutil include:

  • Forgetting to authenticate with Google Cloud SDK before running commands.
  • Using incorrect bucket names or missing the gs:// prefix.
  • Not using the -r flag when copying directories recursively.
  • Confusing local paths and Cloud Storage URLs.
bash
Wrong:
gsutil cp ./folder gs://my-bucket/

Right:
gsutil cp -r ./folder gs://my-bucket/
📊

Quick Reference

CommandDescriptionExample
cpCopy files to/from Cloud Storagegsutil cp file.txt gs://bucket/
lsList buckets or filesgsutil ls gs://bucket/
rmRemove files from Cloud Storagegsutil rm gs://bucket/file.txt
mvMove or rename filesgsutil mv gs://bucket/old gs://bucket/new
rsyncSynchronize directoriesgsutil rsync -r ./local gs://bucket/

Key Takeaways

Always prefix Cloud Storage paths with gs:// when using gsutil commands.
Use gsutil cp to copy files and include -r for directories.
Authenticate with Google Cloud SDK before running gsutil commands.
Use gsutil ls to check bucket contents and verify operations.
Avoid mixing local paths and Cloud Storage URLs without proper syntax.