How To: Get Last Successfully Built Commit for Branch


This article discussed how to retrieve the last successfully built commit for a branch using CircleCI. We provided a code snippet that utilizes the CircleCI API to fetch the necessary information.


In software development, it is crucial to keep track of the last successfully built commit for a specific branch. This information helps developers identify the stable version of the codebase and ensures that any subsequent changes are built upon a reliable foundation. In this article, we will explore how to retrieve the last successfully built commit for a branch using CircleCI.


Before we dive into the code, make sure you have the following requirements in place:
Builds needs to be triggered and the branch should have some builds in the list.
A personal access token from CircleCI (referred to as CIRCLECI_PERSONAL_TOKEN in the code)


To obtain the last successfully built commit for a branch, please use the following script and set the organization name (org_name), project name (prj_name), and branch name (branch_name) variables to specify the desired branch.

# Make an initial request to the CircleCI API to retrieve the pipeline information for the specified branch.
pip=$(curl -s -H "Circle-Token: ${CIRCLECI_PERSONAL_TOKEN}" "${org_name}/${prj_name}/pipeline?branch=${branch_name}")

# Extract the pipeline IDs and their corresponding commit revisions
pipeline_ids=$(echo $pip | jq -r '.items[] | {"id": .id, "revision": .vcs.revision}' )

echo ${pipeline_ids} | jq -c '.' | while read pip; do
pip_id=$(echo $pip | jq -r '.id')
pip_sha=$(echo $pip | jq -r '.revision')
workflow=$(curl -H "Circle-Token: ${CIRCLECI_PERSONAL_TOKEN}"$pip_id/workflow)

# Check if any workflow item has a status of "success"
result=$(echo $workflow | jq -r '.items[] | select(.status == "success")')

# If a successful status is found, print the commit SHA and exit the loop. Otherwise, indicate that a successful status was not found.
if [[ -n "$result" ]]; then
echo "Successful status found. commit sha: $pip_sha"
echo "Successful status not found."


Retrieving the last successfully built commit for a branch is essential for maintaining a stable codebase and ensuring reliable software releases. By using the CircleCI API and the provided code snippet, you can easily obtain this information. Remember to replace the placeholders in the code with your own organization, project, and personal access token.
Was this article helpful?
0 out of 0 found this helpful



Article is closed for comments.