I’ve recently had to get the current branch or the target branch of a PR in Github actions. It took a bit of researching, so I thought it’s worth sharing.

The code below will get the short branch name if the trigger was a push or pull request. Push request contains the full HEAD of the branch ${GITHUB_REF##*/} will extract only the short name.

  - name: Branch used
    id: extract_branch
    run: |
      if [[ "${GITHUB_EVENT_NAME}" == "push" ]]; then
        echo "::set-output name=branch::$(echo ${GITHUB_REF##*/})"
      elif [[ "${GITHUB_EVENT_NAME}" == "pull_request" ]]; then
        echo "::set-output name=branch::$(echo $GITHUB_BASE_REF)"
      else
        echo "::set-output name=branch::INVALID_EVENT_BRANCH_UNKNOWN"
      fi      

After the step runs, you can access the branch name by calling ${{ steps.extract_branch.outputs.branch }} while in the same job.

If you need to pass that value between jobs, add an outputs block to job1, add a needs block to job2.

You can access the value in job2 by accessing the ${{ needs.job1.outputs.extract_branch }} see example below.

  job1:
    name: Get working branch
    runs-on: [ubuntu-latest]
    outputs:
      extract_branch: ${{ steps.extract_branch.outputs.branch }}
    steps:
      - name: Branch used
        id: extract_branch
        run: |
          if [[ "${GITHUB_EVENT_NAME}" == "push" ]]; then
            echo "::set-output name=branch::$(echo ${GITHUB_REF##*/})"
          elif [[ "${GITHUB_EVENT_NAME}" == "pull_request" ]]; then
            echo "::set-output name=branch::$(echo $GITHUB_BASE_REF)"
          else
            echo "::set-output name=branch::INVALID_EVENT_BRANCH_UNKNOWN"
          fi          

  job2:
    needs: job1
    name: I need branch name
    runs-on: [ubuntu-latest]
    env:
      BRANCH: ${{ needs.job1.outputs.extract_branch }}
    run: echo $BRANCH