我正在用Github动作构建Docker图像,并想用分支名称标记图像。

我找到了GITHUB_REF变量,但它导致了refs/heads/feature-branch-1,我只需要feature-branch-1。


当前回答

if: github.ref == 'refs/heads/integration' && github.event_name == 'push' 

您可以使用上面的命令替换您想要运行的任何分支或事件。

其他回答

要将其设置为环境变量,我使用以下语法:

- name: Extract branch name
  shell: bash
  run: echo "::set-env name=BRANCH_NAME::$(echo ${GITHUB_REF#refs/heads/} | sed 's/\//_/g')"
- name: Test
  run: echo "${BRANCH_NAME}"

我发现这个语法在这里:Github动作-启动worflows#如何定义环境变量?# 68

Rmq: sed 's/\//_/g'将用_替换分支名称中的/

在这里重复一下,以便更好地看到其他人在之前的回复中作为简单注释写的内容:

https://docs.github.com/en/actions/learn-github-actions/environment-variables

只在这个环境变量中暴露了pull请求的分支名称:

仅为拉请求事件设置。总行的名称。

在GitHub动作中,对应的上下文键是:

github.head_ref

如何在Github行动中获得当前的分支?

假设${{github。Ref}}类似于refs/heads/mybranch,你可以使用以下方法提取分支名称:

steps:
  - name: Prints the current branch name
    run: echo "${GITHUB_BRANCH##*/}"
    env:
      GITHUB_BRANCH: ${{ github.ref }}

如果你的分支包含斜杠(比如feature/foo),使用下面的语法:

steps:
  - name: Prints the current branch name
    run: echo "${GITHUB_REF#refs/heads/}"

致谢:@rmunn评论

或者使用已接受答案的方法,这里是更短的版本(lint友好):

steps:
  - name: Get the current branch name
    shell: bash
    run: echo "::set-output name=branch::${GITHUB_REF#refs/heads/}"
    id: myref

然后在其他步骤中引用${{steps.myref.outputs.branch}}。

注:

上述方法仅适用于基于unix的映像(Linux和macOS)。 对于文档,请阅读:GitHub Actions的上下文和表达式语法。

获取当前分支很简单,下面的代码适用于我和

github.ref_name

是用于获取分支名称的预定义变量吗

jobs:
  main-branch-build:
    if: github.ref_name == 'main'
    runs-on: ubuntu-latest
    steps:
      - name: Check out code
        uses: actions/checkout@v3
  feature-branch-build:
    if: github.ref_name != 'main'
    runs-on: ubuntu-latest
    steps:
    - name: Check out code
      uses: actions/checkout@v3

现在$ {{github。Ref}}是获取分支名称的正确方法。 请记住${{github。Ref}}有refs/heads/..前缀