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), orrm(remove). - options: Optional flags to modify the command behavior, such as
-rfor 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
-rflag 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
| Command | Description | Example |
|---|---|---|
| cp | Copy files to/from Cloud Storage | gsutil cp file.txt gs://bucket/ |
| ls | List buckets or files | gsutil ls gs://bucket/ |
| rm | Remove files from Cloud Storage | gsutil rm gs://bucket/file.txt |
| mv | Move or rename files | gsutil mv gs://bucket/old gs://bucket/new |
| rsync | Synchronize directories | gsutil 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.