GitHub Actions 使用从 shell 设置的变量

2024-04-20

Goal:

在 GitHub Actions 中,从 shell 动态定义我的提交消息:

      - name: Commit changes
        uses: EndBug/add-and-commit@v7
        with:
          message: "added on $(date -I)"

但是,似乎我必须定义一个环境变量然后使用它。我正在跟进如何在 GitHub Actions 中使用 bash 表达式设置环境变量? https://stackoverflow.com/questions/57968497/和其他帮助文件,例如this https://dev.to/mihinduranasinghe/working-with-environment-variables-github-actions-part-2-46po,但仍然不知道如何使用我之前定义的环境变量。这是我尝试过但失败的:

      - name: Checkout repo
        uses: actions/checkout@v2
      - run: |
          touch sample.js
          echo "today=$(date -I)" >> $GITHUB_ENV

      - name: Commit changes
        uses: EndBug/add-and-commit@v7
        with:
          message: "added on ${today}"

如何让它发挥作用?


如果您想使用以下方式引用环境变量集$GITHUB_ENV环境文件中的另一个任务的参数,您需要使用工作流语法来访问顶层的适当键env关键,像这样:

- name: Commit changes
  uses: EndBug/add-and-commit@v7
  with:
    message: "added on ${{env.today}}"

您可以从正在运行的任务内部将其作为标准环境进行访问,例如:

- name: Show an environment variable
  run: |
      echo "today is $today"

在该示例中,表达式$today被扩展通过外壳, 它查找名为的环境变量today。你也可以 写:

- name: Show an environment variable
  run: |
      echo "today is ${{env.today}}"

在这种情况下,扩展将由 github 的工作流程执行 引擎before the run命令执行,因此 shell 会看到 字面命令看起来像echo "today is 2021-07-14".


您可以使用完成类似的事情输出参数 https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-output-parameter, 像这样:

- name: "Set an output parameter"
  id: set_today
  run: |
    echo "::set-output name=today::$(date -I)"

- name: Commit changes
  uses: EndBug/add-and-commit@v7
  with:
    message: "added on ${{steps.set_today.outputs.today}}"

使用输出参数更加精细(因为它们是 由步骤 ID 限定),并且它们不会出现在环境中 由您的任务启动的进程数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

GitHub Actions 使用从 shell 设置的变量 的相关文章

随机推荐