Actions code:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout codes
uses: actions/checkout@v2
- name: Test git for actions
shell: bash
run: |
## use GitHub variables, such as: GITHUB_REF,GITHUB_HEAD_REF..
BRANCH=${GITHUB_REF##*/}
branch=$BRANCH
git ls-remote --heads --exit-code repo_url "$branch" >/dev/null
if [ "$?" == "1" ]
then
echo "Branch doesn't exist"
else
echo "Branch exist"
fi
It will occur the following error:
BRANCH=${GITHUB_REF##*/}
branch=${BRANCH}
echo $branch
git ls-remote --heads --exit-code repo_url "$branch" >/dev/null
if [ "$?" == "1" ]
then
echo "Branch doesn't exist"
else
echo "Branch exist"
fi
shell: /usr/bin/bash --noprofile --norc -e -o pipefail {0}
main
Error: Process completed with exit code 2.
When I replace ${GITHUB_REF}
with main
, it works fine.
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Test git for actions
shell: bash
run: |
## use GitHub variables, such as: GITHUB_REF,GITHUB_HEAD_REF..
BRANCH=${GITHUB_REF##*/}
branch=main
git ls-remote --heads --exit-code repo_url "$branch" >/dev/null
if [ "$?" == "1" ]
then
echo "Branch doesn't exist"
else
echo "Branch exist"
fi
Output:
BRANCH=${GITHUB_REF##*/}
branch=main
echo $branch
git ls-remote --heads --exit-code repo_url "$branch" >/dev/null
if [ "$?" == "1" ]
then
echo "Branch doesn't exist"
else
echo "Branch exist"
fi
main
Branch exist
Is the git ls-remote
command not able to use variables?
I want to check whether a certain branch exists in the remote warehouse in GitHub Actions.
According to
jobs.<job_id>.steps[*].shell
, the default Bash invocation is:which makes it to fail fast as described under Exit codes and error action preference, for
bash
:And, according to Bash manual, under The Set Builtin:
and,
In your case, the possible solution could be to directly handle the exit status of the command in an
if
:i.e.
or,