简体   繁体   中英

Gsutil - How can I check if a file exists in a GCS bucket (a sub-directory) using Gsutil

I have a GCS bucket containing some files in the path

gs://main-bucket/sub-directory-bucket/object1.gz

I would like to programmatically check if the sub-directory bucket contains one specific file. I would like to do this using gsutil.

How could this be done?

您可以使用gsutil stat命令。

Use the gsutil stat command. For accessing the sub-directories with more number of files use wildcards(*).

For example:

gsutil -q stat gs://some-bucket/some-subdir/*; echo $?

In your case:

gsutil -q stat gs://main-bucket/sub-directory-bucket/*; echo $?

Result 0 means exists ; 1 means not exists

If your script allows for non-zero exit codes, then:

#!/bin/bash

file_path=gs://main-bucket/sub-directory-bucket/object1.gz
gsutil -q stat $file_path
status=$?

if [[ $status == 0 ]]; then
  echo "File exists"
else
  echo "File does not exist"
fi

But if your script is set to fail on error, then you can't use exit codes. Here is an alternative solution:

#!/bin/bash
trap 'exit' ERR

file_path=gs://main-bucket/sub-directory-bucket/object1.gz
result=$(gsutil -q stat $file_path || echo 1)
if [[ $result != 1 ]]; then
  echo "File exists"
else
  echo "File does not exist"
fi

There is also gsutil ls ( https://cloud.google.com/storage/docs/gsutil/commands/ls )

eg

gsutil ls gs://my-bucket/foo.txt

Output is either that same filepath or " CommandException: One or more URLs matched no objects. "

如果出于某种原因您想根据该列表的结果执行某些操作(例如,如果目录上有镶木地板文件,则加载 bq 表):

gsutil -q stat gs://dir/*.parquet; if [ $? == 0 ]; then bq load ... ; fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM