Github-Action: IF语句中是否有ELSE分支?

75

在 Github Action 中,我有一个 if 判断,但是如果进入 else 分支,我仍然需要运行其他的操作。有没有一种简洁的方式来完成这个需求,还是说我必须再写一遍相同条件下为 false 的代码呢?

 - if: contains(['SNAPSHOT'],env.BUILD_VERSION)
   name:IF
   run: echo ":)"
 - if: false == contains(['SNAPSHOT'], env.BUILD_VERSION)
   name: Else
   run: echo ":("

1
我也有一个类似的问题,非常好奇你是如何在工作中集成它的,你能否添加一个指向你GitHub配置文件的链接或者提供更多背景信息? - Dan Chaltiel
6个回答

50

GitHub Actions没有else语句来运行不同的命令/操作/代码。但你是正确的,你所需要做的就是创建另一个步骤并使用反向if条件。顺便说一下,如果你用${{ }}包围你的语句,你可以使用!代替false ==

以下是一些链接:if语句运算符


2
你不能在单个 steps.name 中有多个 if 吗? - Dan Chaltiel
1
你不能使用!,这不是YAML语法的有效代码。为什么你要在没有测试它的情况下编写代码呢? - Peter
20
如果您在${{ }}括号中编写条件,则可以使用!这里有一个例子。 - fabasoad
@DanChaltiel,请查看我的评论,可能对你有用:https://dev59.com/0VIH5IYBdhLWcg3wJ52W#66109820 - lbragile
现在你可以用 else 了。 - Cale
显示剩余2条评论

29

你可以执行以下操作,只有当条件满足时才会运行脚本:

job_name:
  runs-on: windows-latest
  if: "!contains(github.event.head_commit.message, 'SKIP SCRIPTS')"    <--- skips everything in this job if head commit message does not contain 'SKIP SCRIPTS'

  steps:
    - uses: ....
  
    - name: condition 1
      if: "contains(github.event.head_commit.message, 'CONDITION 1 MSG')"
      run: script for condition 1

   - name: condition 2
      if: "contains(github.event.head_commit.message, 'CONDITION 2 MSG')"
      run: script for condition 2

等等。当然,你会使用自己的条件。


17

除了依赖Github Actions命令之外,另一种选择是使用Shell脚本的if else语句。

在Ubuntu机器上,检查提交是否有标签的示例工作流程如下:

runs-on: ubuntu-latest
steps:
  - uses: actions/checkout@v2
  - run: |
      ls
      echo ${{ github.ref }}
      ref='refs/tags/v'
      if [[ ${{ github.ref }} == *${ref}* ]]; then
        v=$(echo ${{ github.ref }} | cut -d'/' -f3)
        echo "version tag is ${v}"
      else
        echo "There is no github tag reference, skipping"
      fi

17

您可以考虑使用 haya14busa/action-cond 动作。当需要进行 if-else 操作来设置其他步骤的动态配置时(无需复制整个步骤以在几个参数中设置不同的值),它非常有用。

示例:

- name: Determine Checkout Depth
  uses: haya14busa/action-cond@v1
  id: fetchDepth
  with:
    cond: ${{ condition }}
    if_true: '0'  # string value
    if_false: '1' # string value
- name: Checkout
  uses: actions/checkout@v2
  with:
    fetch-depth: ${{ steps.fetchDepth.outputs.value }}

11

我发现我们也可以在这里使用表达式来实现:

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      PkgDesc: ${{ github.event.inputs.packageDescription != '' && github.event.inputs.packageDescription ||  format('{0} - {1}', 'Commit', github.SHA)  }}

语法:${{ x && 'ifTrue' || 'ifFalse' }}

更多细节请参见https://github.com/actions/runner/issues/409#issuecomment-752775072


1
这应该是被接受的答案。 - undefined

0

如果您想检查某个数据类型的值而不使用内置函数,也可以像这样做

- name: Notify Team on Slack
   if: ${{github.repository == 'calebcadainoo/cascade-img'}}
   run: |
     # some command

在这里,我每次推送时都会触发事件。

我同时向两个仓库推送,但我只想运行一次命令。

在此处阅读有关表达式的更多信息:

https://docs.github.com/en/actions/learn-github-actions/expressions


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接