Skip to content

Instantly share code, notes, and snippets.

@mshafiee
Created February 4, 2023 15:14
Show Gist options
  • Save mshafiee/106765245ddbc5b66a12e3e9b650e93e to your computer and use it in GitHub Desktop.
Save mshafiee/106765245ddbc5b66a12e3e9b650e93e to your computer and use it in GitHub Desktop.
This bash script will check if a branch named BRANCH_NAME exists in the Git repository. If it exists, it will checkout to that branch and reset the branch to the previous commit, discarding all previous commits except the last one. It will then rename the latest commit to COMMIT_NAME and push the rewritten branch to the remote repository. Finall…
#!/bin/bash
# This bash script will check if a branch named BRANCH_NAME exists in the Git repository.
# If it exists, it will checkout to that branch and reset the branch to the previous commit,
# discarding all previous commits except the last one. It will then rename the latest
# commit to COMMIT_NAME and push the rewritten branch to the remote repository.
# Finally, it will display a message indicating that the branch has been rewritten
# and the last commit has been renamed.
if [ $# -ne 2 ]; then
echo "Error: Invalid number of arguments."
echo "Usage: ./resetBranch.sh BRANCH_NAME COMMIT_NAME"
exit 1
fi
BRANCH_NAME=$1
COMMIT_NAME=$2
# Check if branch exists
if git rev-parse --verify $BRANCH_NAME > /dev/null 2>&1; then
echo "Branch $BRANCH_NAME found"
else
echo "Branch $BRANCH_NAME not found. Exiting."
exit 1
fi
# Checkout branch
git checkout $BRANCH_NAME
# Get the number of commits in the branch
num_commits=$(git rev-list --count HEAD)
# Reset branch to the previous commit, discarding all commits except the last one
git reset --hard HEAD~$((num_commits))
# Rename the latest commit
git commit --amend -m "$COMMIT_NAME"
# Push the rewritten branch to remote repository
git push -f origin $BRANCH_NAME
echo "Branch $BRANCH_NAME has been rewritten with the last commit renamed to $COMMIT_NAME"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment