'Use environment variable in github action if

I'm trying to use an environment variable in an if condition in github actions like so:

name: Worfklow
on:
  push

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v1

      - name: EXIT step
        if: $GITHUB_REF == 'specific-branch'
        run: exit 1

I want to exit if the current branch is equal to a specific branch.

Unfortunately, the github actions console displays an error:

Unexpected symbol: '$GITHUB_REF'

I can use $GITHUB_REF in a run: (where it contains the current branch), but not in an if:. What am I doing wrong?



Solution 1:[1]

do it like this:

if: github.ref == 'specific-branch'

reference branch conditional

Solution 2:[2]

Though the original problem had been solved without environment vars, I'd like to share how it can be used with if conditions.

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:

      - name: Set env BRANCH
        run: echo "BRANCH=$(echo $GITHUB_REF | cut -d'/' -f 3)" >> $GITHUB_ENV

      - name: Set env NEED
        run: |
          if [[ $BRANCH == 'master' && $GITHUB_EVENT_NAME == 'push' ]]; then
              echo "NEED=true" >> "$GITHUB_ENV"
          else
              echo "NEED=false" >> "$GITHUB_ENV"
          fi

      - name: Skip Deploy?
        if: env.NEED != 'true'
        run: echo "Only pushing to 'master' causes automatic deployment"

     ...

The first two steps set 2 env variables, the third step demonstrates what syntax you need to follow to use these vars in if conditions.

Solution 3:[3]

You can use some restrictions on the push section of the action

on:
  push:
    branches:    
      - '*'         # matches every branch that doesn't contain a '/'
      - '*/*'       # matches every branch containing a single '/'
      - '**'        # matches every branch
      - '!master'   # excludes master

This answer was taken from this stack overflow question

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DᴀʀᴛʜVᴀᴅᴇʀ
Solution 2 dhilt
Solution 3 matias