During a GitHub action, I'd like to know the name of the branch:
I need a string like develop
, master
or feature/xxx
(and not refs/pull/…).
The ${{ github.ref }}
var gives me refs/heads/develop
. How can I get only the develop
?
github.head_ref. string. The head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target . github.job.
In order to add branch name to bash prompt we have to edit the PS1 variable(set value of PS1 in ~/. bash_profile). This git_branch function will find the branch name we are on. Once we are done with this changes we can nevigate to the git repo on the terminal and will be able to see the branch name.
Update: GitHub added the context variable ${{ github.ref_name }}
, returning "The branch or tag name that triggered the workflow run."
Original Answer:
You can create a step output of the last part of GITHUB_REF
like the following.
on: push
jobs:
example:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set output
id: vars
run: echo ::set-output name=short_ref::${GITHUB_REF#refs/*/}
- name: Check output
run: echo ${{ steps.vars.outputs.short_ref }}
This creates an environment variable GIT_BRANCH which has the following behavior:
master
, not refs/heads/master
)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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With