Script for recreating a branch from the main branch

Script for recreating a branch from the main branch

Many a times we need to delete and recreate a branch both locally and remotely and sync it with the main branch. In our firm too we were doing this a lot of times. So, we decided to write a shell script to ease this task. We will be discussing that in this blog post.

read -p $'\e[31mEnter "yes" to delete your branch & recreate it from main:\e[0m ' CONT
BRANCH="${1:-defaultBranch}"  # If variable not set or null, set it to default.

if [ "$CONT" = "y" ]; then
  git checkout main
  git branch -d ${BRANCH} #delete locally
  git push origin --delete ${BRANCH} #delete remotely
  git pull origin main
  git checkout -b ${BRANCH}
  git push origin ${BRANCH}
  echo "${BRANCH} branch recreated succesfully from main"
else
  echo "Cancelled!";
fi

Here, the dev will be prompted with a user confirmation which will only proceed when the dev types 'y'. The branch to be deleted and recreated is to be given through the argument. Put the script in yourShell.sh and place it at the root of your project. Run it like this:-

sh yourShell dummyBranch

If there is no branch provided through the argument then the defaultBranch will be deleted and recreated. Got the basic idea from this blog.