github操作:IF有ELSE吗github操作中的



我有一个if,但如果我在其他情况下,我仍然需要运行其他东西。有没有一种干净的方法可以做到这一点,或者我必须在false的相同条件下再做一步?

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

GitHub Actions没有else语句来运行不同的命令/action/代码。但您是对的,您所需要做的就是创建另一个具有反向if条件的步骤。顺便说一句,如果你用${{ }}包围你的陈述,你可以只使用!而不是false ==

以下是一些链接:if语句、操作员

您可以执行以下操作,这些操作只会在条件通过时运行脚本:

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

等等。你当然会在这里使用你自己的条件。

您可以考虑使用haya14usa/action第二个操作。当需要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 }}

基于github操作的命令的替代解决方案是为if-else语句使用shell脚本命令。

在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

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

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

如果您想在不使用内置函数的情况下检查某些数据类型值,也可以执行类似的操作

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

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

我正在同时推动两个回购,但我只想运行我的命令一次。

点击此处阅读更多表达式:

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

最新更新