【问题标题】:Check if git remote exists before first push在第一次推送之前检查 git remote 是否存在
【发布时间】:2012-08-23 14:55:49
【问题描述】:

我正在编写一个 bash 脚本,我需要一个测试来查看给定的远程是否存在。

假设,具体来说,我想测试远程faraway 是否存在。如果我向faraway 推送了一些东西,我可以做if [ -d .git/refs/remotes/faraway ]; then ...。但据我所知,即使.git/refs/remotes/faraway 不存在,别名faraway 仍然可以定义。

另一种选择是解析git remote 的输出并查看faraway 是否出现在那里。但我想知道是否有更简单的方法来检查是否定义了faraway,无论.git/refs/remotes/faraway/ 是否存在。

【问题讨论】:

    标签: git bash


    【解决方案1】:

    一个想法:您可以在git ls-remote faraway 上测试退出状态。这实际上会强制与远程通信,而不是仅仅在本地寻找它的存在或不存在。

    git ls-remote --exit-code faraway
    if test $? = 0; then
        ....
    fi
    

    【讨论】:

    • 这可以简化为if git ls-remote faraway ...。不需要测试命令。
    • 优秀。谢谢!我假设在faraway 不存在时避免在输出中获取fatal ... 的标准方法是将&>/dev/null 添加到第一行的末尾?
    • @apc 使用帮助中有一个--quiet 标志,但它不在手册页中,它似乎没有做任何事情。
    • @apc 啊哈。是的,您需要重定向到/dev/null。当 git ls-remote 不带参数发出时,--quiet 标志为 added to silence a single line。
    • 现在看来您必须添加 `--exit-code 选项,否则该命令仅在无法到达远程时才以非 0 存在。 See here
    【解决方案2】:

    如果远程是在.git/config 中定义的,你可以避免用git remote ping 远程服务器。

    if git remote | grep faraway > /dev/null; then
      ...
    fi
    

    【讨论】:

    • 这是一个子字符串搜索,因此如果您有其他包含 faraway 的遥控器,它可能会给出误报。
    【解决方案3】:

    另一种检查faraway 是否在.git/config 中定义的方法:

    if git config remote.faraway.url > /dev/null; then
      …
    fi
    

    要检查faraway是否没有定义,请在条件前加上!:

    if ! git config remote.faraway.url > /dev/null; then
      …
    fi
    

    【讨论】:

    • 这很有帮助,尤其是如果您想防止远程往返。
    • 如果未定义,检查负数的最佳方法是什么?
    • @rveach 只是前缀!,所以if ! git config remote.faraway.url > /dev/null; then
    • 从什么时候开始 bash 支持不包含 [] 甚至 [[]] 的条件语句?
    • @WestCoastProjects 命令退出码使用,没有比较,所以不需要括号
    猜你喜欢
    • 2018-12-21
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    相关资源
    最近更新 更多