10.01.2018

Bash script for switching branches in Git

This script follows my workflow of switching between different branches in my dev environment:
1. Stash changes in my current branch.
2. Checkout the other branch.
3. Apply previously saved stash on the switched branch.
#!/bin/bash

echo "Switching to $1 branch..."
BRANCH=$(git branch | grep \* | cut -d ' ' -f2)
STASHNAME="$BRANCH-changes"
git stash save "$STASHNAME"
git checkout $1
LATEST=$(git stash list | grep $1 | head -n 1)
echo "Latest stash: $LATEST"
echo "Do you want to apply this stash? [y/n]: "
read apply_stash
if [ "$apply_stash" == "y" ]; then
    STASHED=$(git stash list | grep $1 | head -n 1 | cut -d ":" -f1)
    git stash apply "$STASHED"
fi