You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitHub Action同一步骤中,命令返回非零码时如何继续执行?

解决GitHub Action中命令失败后仍执行同步骤后续操作的问题

GitHub Action的Bash脚本默认启用了set -e(errexit)模式,即任何命令返回非零退出码时,脚本会立即终止执行——这就是你遇到的问题:git ls-remote失败时,后续的if-else逻辑根本没机会运行。下面提供两种可行的解决方案:

方案1:为目标命令追加|| true

在可能失败的命令后加上|| true,让这条命令的整体退出码始终为0,避免触发脚本终止,同时原命令的退出码会保留在$?中供后续判断:

run: |
        BRANCH_NAME=${{ steps.set_branch_name_from_pr.outputs.BRANCH_NAME || steps.set_branch_name_from_commit.outputs.BRANCH_NAME }}
        git ls-remote --exit-code --heads https://x-access-token:${GITHUB_TOKEN}@github.com/afkl-airspace/tresorro-tresor-ro.git refs/heads/$BRANCH_NAME || true
        # If the branch exists, no error and we delete it
        if [[ $? -eq 0 ]]; then
          git push origin --delete $BRANCH_NAME
        else
          echo "Remote branch [$BRANCH_NAME] does not exist"
        fi

方案2:直接将命令嵌入if条件判断

利用Bash中if语句的特性:if会执行紧跟的命令,并根据命令的退出码选择分支,即使命令失败也不会终止脚本。这种写法更简洁直观,无需单独处理$?:

run: |
        BRANCH_NAME=${{ steps.set_branch_name_from_pr.outputs.BRANCH_NAME || steps.set_branch_name_from_commit.outputs.BRANCH_NAME }}
        # If the branch exists, delete it; else print message
        if git ls-remote --exit-code --heads https://x-access-token:${GITHUB_TOKEN}@github.com/afkl-airspace/tresorro-tresor-ro.git refs/heads/$BRANCH_NAME; then
          git push origin --delete $BRANCH_NAME
        else
          echo "Remote branch [$BRANCH_NAME] does not exist"
        fi

两种方案都能实现需求,其中方案2逻辑更清晰,是更推荐的写法。

内容的提问来源于stack exchange,提问作者PrOpoLo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:33:21