This creates an environment variable GIT_BRANCH which has the following behavior:
- Outside of a PR, this is set to the branch short name (
master
, not refs/heads/master
)
- Inside a PR, this is set to the target branch short name (
master
, not refs/pull/123/merge
)
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Set environment variables
run: |
# Short name for current branch. For PRs, use target branch (base ref)
GIT_BRANCH=${GITHUB_BASE_REF:-${GITHUB_REF#refs/heads/}}
echo "GIT_BRANCH=$GIT_BRANCH" >> $GITHUB_ENV
How this works:
- GITHUB_BASE_REF is the short branch name for the target branch during a PR trigger, and it is empty otherwise.
- GITHUB_REF always has a value, but the value changes based on the context. Outside of a PR, GITHUB_REF is the "full" branch name (
refs/heads/master
). Inside of a PR, it is the PR branch name (refs/pull/123/merge
).
So this script uses GITHUB_BASE_REF if set, otherwise it uses GITHUB_REF and removes the "refs/heads/" prefix.