🎓 A1Learner
🔍
0 of 50 lessons completed

GitHub Actions: Conditions with if

An if condition runs a step only when a test holds. A step that fails its test is skipped, not failed.

Only on the main branch

The built-in value github.ref names the branch that was pushed. Main is refs/heads/main.

      - run: echo "On main branch"
        if: github.ref == 'refs/heads/main'

Only on a push

The built-in value github.event_name names the event that started the run.

      - run: echo "Started by a push"
        if: github.event_name == 'push'

Only when a step fails

The failure() test is true only when an earlier step failed.

      - run: echo "Tests failed"
        if: failure()

Only when a step passes

The success() test is true when every earlier step passed.

      - run: echo "Tests passed"
        if: success()

Example

name: Conditions
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: '24'
      - run: npm test
      - run: echo "On main branch"
        if: github.ref == 'refs/heads/main'
      - run: echo "Tests failed"
        if: failure()

Key points

  • Use if on a step to run it only when a condition holds.
  • Use if on a job to run the whole job only when a condition holds.
  • A skipped step does not fail the job.
  • Use failure() to run a step only when an earlier step failed.
  • A step runs by default when it has no if line.
  • An if condition is a small test before the step, stated in plain words.

In this example, the workflow is saved as .github/workflows/conditions.yml. The test step runs first and passes. The next step has an if line that checks the branch, so it runs only on a push to main. The last step uses failure(), so it runs only when an earlier step fails. The output shows both tests passing and the main-branch line. The last step was skipped because nothing failed.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

A step has if: failure(). When does it run?