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

GitHub Actions中if条件异常:始终执行true分支问题

GitHub Actions条件分支始终执行true分支的解决方法

问题原因

你在bash的if [ ... ]中使用了GitHub Actions表达式,渲染后会生成字符串"true"或"false"。在bash语法里,非空字符串都会被视为真值,哪怕是"false"字符串,if [ "false" ]也会执行true分支。另外,schedule触发时github.event.inputs.typeOfTesting为空,你当前的npm命令逻辑也存在疏漏。

修复方案

以下两种方式都可以解决问题,推荐第一种(纯bash判断,更直观易维护):

方法一:纯bash变量判断

将GitHub输入变量赋值给bash本地变量,在bash内部完成条件判断:

workflow_dispatch:
    inputs:
      typeOfTesting:
        type: choice
        description: Select Type of Test
        default: "stage-test-Uptime"
        required: true
        options:
          - stage-test-Uptime
          - prod-test-Uptime
  schedule:
    - cron: "30 3 * * *"
    - cron: "30 13 * * *"

 steps:
      - name: Show Testing Type
        run: |
          echo "Testing Type: ${{ github.event.inputs.typeOfTesting }}"
      - name: Install Dependencies
        run: npm install
      - name: Run Test
        run: |
          # 赋值并处理schedule触发时的空值情况
          TEST_TYPE="${{ github.event.inputs.typeOfTesting }}"
          if [[ -z "$TEST_TYPE" || "$TEST_TYPE" == "stage-test-Uptime" ]]; then
            echo "action_state=https://hooks.slack.com/services/XXX/XXX/XXX" >> $GITHUB_ENV
          else
            echo "action_state=https://hooks.slack.com/services/YYY/YYY/YYY" >> $GITHUB_ENV
          fi
          # 空值时默认执行stage-test-Uptime
          npm run "${TEST_TYPE:-stage-test-Uptime}"

方法二:直接使用GitHub表达式控制bash逻辑

去掉if后的[ ],让GitHub表达式渲染后的true/false直接作为bash内置命令执行(bash的true命令返回0,false返回非0,符合if判断逻辑):

workflow_dispatch:
    inputs:
      typeOfTesting:
        type: choice
        description: Select Type of Test
        default: "stage-test-Uptime"
        required: true
        options:
          - stage-test-Uptime
          - prod-test-Uptime
  schedule:
    - cron: "30 3 * * *"
    - cron: "30 13 * * *"

 steps:
      - name: Show Testing Type
        run: |
          echo "Testing Type: ${{ github.event.inputs.typeOfTesting }}"
      - name: Install Dependencies
        run: npm install
      - name: Run Test
        run: |
          if ${{ github.event.inputs.typeOfTesting == '' || github.event.inputs.typeOfTesting == 'stage-test-Uptime' }}; then
            echo "action_state=https://hooks.slack.com/services/XXX/XXX/XXX" >> $GITHUB_ENV
          else 
            echo "action_state=https://hooks.slack.com/services/YYY/YYY/YYY" >> $GITHUB_ENV
          fi
          npm run ${{ github.event.inputs.typeOfTesting == '' && 'stage-test-Uptime' || github.event.inputs.typeOfTesting }}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:05:46