如果不存在文件,则处理 gsutil ls 和 rm 命令错误
Handle gsutil ls and rm command errors if no files present
我是 运行 以下命令,用于在加载新文件之前从 gcs 存储桶中删除文件。
gsutil -m rm gs://mybucket/subbucket/*
如果桶中没有文件,它会抛出 "CommandException: One or more URLs matched no objects"。
我希望它在不抛出错误的情况下删除文件(如果存在)。
与gsutil ls gs://mybucket/subbucket/*
有同样的错误
如何在不必显式处理异常的情况下重写它?或者,如何在批处理脚本中最好地处理这些异常?
试试这个:
gsutil -m rm gs://mybucket/foo/* 2> /dev/null || true
或者:
gsutil -m ls gs://mybucket/foo/* 2> /dev/null || true
这具有抑制 stderr(指向 /dev/null
)的效果,并且即使在失败时也返回成功错误代码。
您可能不想忽略所有错误,因为它可能表示未找到文件的不同之处。使用以下脚本,您将仅忽略 'One or more URLs matched not objects' 但会通知您一个不同的错误。如果没有错误,它只会删除文件:
gsutil -m rm gs://mybucket/subbucket/* 2> temp
if [ $? == 1 ]; then
grep 'One or more URLs matched no objects' temp
if [ $? == 0 ]; then
echo "no such file"
else
echo temp
fi
fi
rm temp
这会将 stderr 通过管道传输到临时文件并检查消息以决定是忽略它还是显示它。
而且它也适用于单个文件删除。希望对你有帮助。
参考文献:
How to grep standard error stream
Bash Reference Manual - Redirections
您可能喜欢 rsync 将文件和文件夹同步到存储桶。我用它来清除存储桶中的文件夹并将其替换为我的构建脚本中的新文件。
gsutil rsync -d newdata gs://mybucket/data
- 用 newdata
替换 data
文件夹
我是 运行 以下命令,用于在加载新文件之前从 gcs 存储桶中删除文件。
gsutil -m rm gs://mybucket/subbucket/*
如果桶中没有文件,它会抛出 "CommandException: One or more URLs matched no objects"。
我希望它在不抛出错误的情况下删除文件(如果存在)。
与gsutil ls gs://mybucket/subbucket/*
如何在不必显式处理异常的情况下重写它?或者,如何在批处理脚本中最好地处理这些异常?
试试这个:
gsutil -m rm gs://mybucket/foo/* 2> /dev/null || true
或者:
gsutil -m ls gs://mybucket/foo/* 2> /dev/null || true
这具有抑制 stderr(指向 /dev/null
)的效果,并且即使在失败时也返回成功错误代码。
您可能不想忽略所有错误,因为它可能表示未找到文件的不同之处。使用以下脚本,您将仅忽略 'One or more URLs matched not objects' 但会通知您一个不同的错误。如果没有错误,它只会删除文件:
gsutil -m rm gs://mybucket/subbucket/* 2> temp
if [ $? == 1 ]; then
grep 'One or more URLs matched no objects' temp
if [ $? == 0 ]; then
echo "no such file"
else
echo temp
fi
fi
rm temp
这会将 stderr 通过管道传输到临时文件并检查消息以决定是忽略它还是显示它。
而且它也适用于单个文件删除。希望对你有帮助。
参考文献:
How to grep standard error stream
Bash Reference Manual - Redirections
您可能喜欢 rsync 将文件和文件夹同步到存储桶。我用它来清除存储桶中的文件夹并将其替换为我的构建脚本中的新文件。
gsutil rsync -d newdata gs://mybucket/data
- 用 newdata
data
文件夹