How to switch and save without commit in git?

Viewed 25709

I am working on one branch, and suddenly I have to switch to another branch to fix an urgent bug. The problem is the changes I make to the current branch is still a mess and I do not want to commit that and leave some scrappy commit message.

Is there any way I can save the current changes without commit?

3 Answers

This is a neat little bash function I set up inspired by @jingx's answer:

gcl() { 
    echo "### Adding any wip files";
    git add .; 
    echo "### Committing files with a temporary commit";
    git commit --no-verify -am 'local commit - work in progress';
    echo "### Checking out branch";
    git checkout "$1";
    x="$(git log -1 --pretty=%B)"
    if [ "$x" = "local commit - work in progress" ]; then
        echo "### Undoing last commit";
        git reset --soft HEAD^
    else 
        echo "### Not undoing last commit"
    fi
    echo "gcl complete"
}

Add it to your .bashrc or .profile and then use gcl my-branch to switch branches and save your work as a local commit and simultaneously unpack your local commits on change.


For example, say you're on branch1 and have uncommitted changes. Just do a

gcl urgent-fix

do whatever you need to do and then hop back

gcl branch1

Your uncommitted changes will be there just like you left them.

Although a commit does take place, it isn't pushed remotely and so can be undone locally without consequence.

Related