Search code examples
yamlgithub-actions

How to get branch name in a Github Action Shell script


I'm trying to create an output to use later in the job.

However, for some reason, the BRANCH env variable which I'm getting to be the GITHUB_REF_NAME is an empty string, which according to the docs, should be the branch.

Also using the variable directly produces the same result.

      - name: Set Terraform Environment Variable
        id: set_tf_env
        env:
          BRANCH: ${{env.GITHUB_REF_NAME}}
        run: |
          if [ "$BRANCH" == "dev" ]; then
              run: echo "::set-output name=TF_ENV::dev"
              elif [ "$BRANCH" == "prod" ]; then
              run: echo "::set-output name=TF_ENV::prod"
          else
              echo "Branch has no environment"
              exit 1
          fi


Solution

  • So after a bit of more research and thanks to the comments, I discovered the reason why it wasn't working.

    It was because I was triggering a GitHub action in a Pull Request, something I failed to mention.

    So what I ended up using was:

    github.event.pull_request.head.ref