4

Seeking a solution to achieve the following:

  • If a branch is not current created on local create
  • If it already exists prompt user and move to next statement

So far I've got it working but not quite there. My issue really is the latter, but I want to take a moment to rethink the whole thing and get some feedback on how to write this more soundly.

The variable existing_branch provides SHA and the refs/heads/branchName when a branch is there otherwise git takes hold and provides the expected fatal:

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
}

1 Answer 1

7

You can avoid prompting if the branch already exists, and shorten the script a little, like this:

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you this worked as I intended. New to bash scripting, care to explain how to use the curly braces and technique in line 2 and line 5 a bit more?
Check out parameter expansion, in POSIX or bash, and redirection. >&2 means that echo goes to stderr, rather than stdout.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.