【问题标题】:Handle gsutil ls and rm command errors if no files present如果不存在文件,则处理 gsutil ls 和 rm 命令错误
【发布时间】:2017-08-13 10:47:19
【问题描述】:

在加载新文件之前,我正在运行以下命令从 gcs 存储桶中删除文件。

gsutil -m rm gs://mybucket/subbucket/*

如果存储桶中没有文件,则抛出“CommandException:一个或多个 URL 匹配没有对象”。

如果存在,我希望它删除文件而不抛出错误。

gsutil ls gs://mybucket/subbucket/*也有同样的错误

如何在不必明确处理异常的情况下重写它?或者,如何在批处理脚本中最好地处理这些异常?

【问题讨论】:

    标签: gsutil


    【解决方案1】:

    试试这个:

    gsutil -m rm gs://mybucket/foo/* 2> /dev/null || true
    

    或者:

    gsutil -m ls gs://mybucket/foo/* 2> /dev/null || true
    

    这具有抑制 stderr 的效果(它被定向到/dev/null),即使失败也返回成功错误代码。

    【讨论】:

    • 谢谢。我确实将其更改为在 Windows 批处理脚本中遵循。 gsutil -m rm gs://mybucket/foo/* 2>nul || true
    【解决方案2】:

    您可能不想忽略所有错误,因为它可能表示未找到该文件的不同内容。使用以下脚本,您将仅忽略“一个或多个与对象不匹配的 URL”,但会通知您另一个错误。如果没有错误,它只会删除文件:

    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

    【讨论】:

    • 错误更改为“CommandException: 1 个文件/对象无法删除。”
    【解决方案3】:

    您可能希望rsync 将文件和文件夹同步到存储桶。我用它来清除存储桶中的文件夹并用我的构建脚本中的新文件替换它。

    gsutil rsync -d newdata gs://mybucket/data - 用 newdata 替换 data 文件夹

    【讨论】:

    • gsutil rsync -d -r newdata gs://mybucket/data 可能是您想要递归同步的内容
    猜你喜欢
    • 2014-05-03
    • 2011-07-10
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 2018-03-08
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多