Commit the working directory to different branch and switch back
Putting it through shellcheck.net results in quite a lot of cleanups.

Apart from the issues raised there, I'd suggest that at the end of your script, you might want to git stash pop instead of git stash apply when restoring your state.

Inside the function body, you may use local to declare the BEFORE variable. While local is not POSIX compliant, all of GNU and BSD compliant shells support the local keyword.