switchtobranch.sh 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/bin/bash
  2. branches=`git for-each-ref --format='%(refname:short)' refs/heads`;
  3. branchexists=false;
  4. for branch in ${branches}; do
  5. if [ "$branch" = "$1" ]; then
  6. branchexists=true;
  7. break;
  8. fi
  9. done
  10. if [ "$branchexists" == false ]; then
  11. echo "Branch $1 does not exist"
  12. exit 1
  13. fi
  14. read -n1 -p "Switching to branch $1. Save changes on this branch? (Y/N/Q): " answer;
  15. if [ "$answer" == "Y" ] || [ "$answer" == "y" ]; then
  16. echo "Saving changes...";
  17. git add .;
  18. git commit -m "Saving changes before switching to branch $1";
  19. git push -u origin $1;
  20. elif [ "$answer" == "N" ] || [ "$answer" == "n" ]; then
  21. echo "Discarding changes...";
  22. git reset --hard;
  23. elif [ "$answer" == "Q" ] || [ "$answer" == "q" ]; then
  24. printf "\nQuitting...";
  25. exit 0;
  26. else
  27. echo "Invalid input. Quitting...";
  28. exit 1;
  29. fi
  30. echo "Switching to branch $1...";
  31. checkoutresult=`git checkout $1`;
  32. echo $checkoutresult
  33. if [ "$checkoutresult" == *"Switched to branch '$1'"* ]; then
  34. echo "Switched to branch $1";
  35. else
  36. echo "Failed to switch to branch $1";
  37. exit 1;
  38. fi
  39. echo "Installing node_modules for branch...";
  40. npm install;
  41. echo "Finished switching to branch $1";
  42. exit 0;