How to Bash Script Git Checkout Local Branch?

Finding a solution to achieve the following:

  • If branch is not created in local create structure
  • If it already exists, query the user and move on to the next statement

So far it works for me, but not quite there. My problem is actually the last one, but I want to take a minute to rethink the whole thing and get some feedback on how to write this more reliably.

Variable existing_branch

provides SHA and refs / heads / branchName when branch otherwise git grabs and provides expectedfatal:

check_for_branch() {
 args=("$@")
 echo `$branch${args[0]}`
 existing_branch=$?
}

create_branch() {
  current="git rev-parse --abbrev-ref HEAD"
  branch="git show-ref --verify refs/heads/"

  args=("$@")
  branch_present=$(check_for_branch ${args[0]})
  echo $branch_present
  read -p "Do you really want to create branch $1 " ans
  case $ans in
    y | Y | yes | YES | Yes)
        if [  ! -z branch_present ]; then
          echo  "Branch already exists"
        else
          `git branch ${args[0]}`
          echo  "Created ${args[0]} branch"
        fi
    ;;
     n | N | no | NO | No)
      echo "exiting"
    ;;
    *)
    echo "Enter something I can work with y or n."
    ;;
    esac
}

      

+3


source to share


1 answer


You can choose not to ask if a branch exists and shorten the script a bit, for example:



create_branch() {
  branch="${1:?Provide a branch name}"

  if git show-ref --verify --quiet "refs/heads/$branch"; then
    echo >&2 "Branch '$branch' already exists."
  else
    read -p "Do you really want to create branch $1 " ans
    ...
  fi
}

      

+6


source







All Articles