Run if a file is changed

Hi,
I would like to run a particular job if a particular file has been changed.

Consider the following .gitlab-ci.yml:

stages:
- test

always:
  stage: test
  image: alpine
  script:
    - env | sort

change:
  stage: test
  image: alpine
  rules:
    - changes:
        paths:
        - dir/file
  script:
    - echo "dir/file"

If I modify and commit to the default (main) branch:

  • the dir/file, it triggers both the always and change job
  • any other file it will trigger only the always job

as expected.

Instead If I modify and commit to any other branch (ie create a merge request) it will run both jobs even if I do not modify the dir/file file.

Am I missing something?

Thanks

For future reference:

---
stages:
  - test

always:
  stage: test
  image: alpine
  script:
    - env | sort

change:
  stage: test
  image: alpine
  rules:
    # `rules.changes` only filters with branch pipelines or merge request pipelines, otherwise is true
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        paths:
          - dir/file
        compare_to: main
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      changes:
        - dir/file
  script:
    - echo "dir/file"
  • push to main and not modifying dir/file, always job is triggered
  • push to main and modifying dir/file, always and change jobs is triggered
  • push to branch and not modifying dir/file, always job is triggered
  • push to branch and modifying dir/file, always and change jobs is triggered