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

Github Action在Docker镜像中不识别[[...]]语句的解决求助

GitHub Action [[语法报错导致无限循环的解决办法

问题背景

我有一个GitHub Action,用于PR从release/**分支合并到master时自动递增RC版本号并提交回release分支。为避免触发无限循环,我添加了如下检查步骤:

- name: Check if version number has changed
        run: |
          if [[ $(git show HEAD | grep -e "\"version\":.*-rc\..*") ]]; then
            echo "Version number has changed, moving onto next jobs"
            exit 1
          else
            echo "Version number has not changed, continuing with this job"
          fi

运行时却报错:

1: [[: not found
Version number has not changed, continuing with this job

这个错误导致检查逻辑失效,触发了无限循环。我试过切换到ubuntu:latest镜像、在脚本开头加#!/bin/bash,都没用,而本地WSL Ubuntu环境中这个语句能正常运行。

问题原因

GitHub Action的run步骤默认使用sh(Ubuntu镜像中是dash)而非bash,[[是bash专属的扩展语法,sh不支持,因此会报错,进而导致分支判断走了else分支,触发后续版本递增逻辑,形成循环。

修复方案

方案1:改用POSIX兼容的[语法

把[[ ... ]]替换为[ ... ],同时用-n检查输出是否非空:

- name: Check if version number has changed
        run: |
          if [ -n "$(git show HEAD | grep -e "\"version\":.*-rc\..*")" ]; then
            echo "Version number has changed, moving onto next jobs"
            exit 1
          else
            echo "Version number has not changed, continuing with this job"
          fi

方案2:强制使用bash执行

在步骤中明确指定用bash运行脚本,有两种方式:

方式A:设置shell字段为bash

- name: Check if version number has changed
        shell: bash
        run: |
          if [[ $(git show HEAD | grep -e "\"version\":.*-rc\..*") ]]; then
            echo "Version number has changed, moving onto next jobs"
            exit 1
          else
            echo "Version number has not changed, continuing with this job"
          fi

方式B:通过bash -c调用

- name: Check if version number has changed
        run: bash -c 'if [[ $(git show HEAD | grep -e "\"version\":.*-rc\..*") ]]; then echo "Version number has changed, moving onto next jobs"; exit 1; else echo "Version number has not changed, continuing with this job"; fi'

优化版检查逻辑

可以直接利用grep的退出码判断,无需捕获输出,更高效:

- name: Check if version number has changed
        shell: bash
        run: |
          if git show HEAD | grep -q -e "\"version\":.*-rc\..*"; then
            echo "Version number has changed, moving onto next jobs"
            exit 1
          else
            echo "Version number has not changed, continuing with this job"
          fi

-q参数让grep静默运行,找到匹配时返回0,未找到返回1,直接用于if判断即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:05:18