我有一个GCS存储桶,其中包含路径下的一些文件
gs://main-bucket/sub-directory-bucket/object1.gz
我想通过编程方式检查子目录存储桶是否包含特定文件。我想使用gsutil来完成此操作。
如何实现?
我有一个GCS存储桶,其中包含路径下的一些文件
gs://main-bucket/sub-directory-bucket/object1.gz
我想通过编程方式检查子目录存储桶是否包含特定文件。我想使用gsutil来完成此操作。
如何实现?
如果你的脚本允许非零退出码,则:
#!/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
但如果你的脚本设置为在错误时失败,那么你就不能使用退出代码。这里有一种替代方案:
#!/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
gsutil stat gs://bucket/dir/subdir/foo.txt
就可以正常工作。我会提交一个错误报告,以便更新文档并使其更加清晰明了。 - jterrace例如:
gsutil -q stat gs://some-bucket/some-subdir/*; echo $?
就您的情况而言:
gsutil -q stat gs://main-bucket/sub-directory-bucket/*; echo $?
结果0表示存在;1表示不存在
还有一个gsutil ls
命令( https://cloud.google.com/storage/docs/gsutil/commands/ls)
例如:
gsutil ls gs://my-bucket/foo.txt
输出要么是相同的文件路径,要么是 "CommandException: One or more URLs matched no objects.
"。
只需使用ls命令并计算输出行数即可。
如果为0,则文件不存在,如果为1,则文件存在。
file_exists=$(gsutil ls gs://my_bucket/object1.gz | wc -l)
当然,同样的方法可以用于许多文件。
files_number=$(gsutil ls gs://my_bucket/object* | wc -l)
if [ "$(gsutil -q stat $file_path ; echo $?)" = 0 ]
的语句,而不是设置陷阱。 - bfontaine