2
\$\begingroup\$

The aim of this script is to snapshot the current working directory of a git repository to another branch. Afterwards, it switches back to the original branch and restores the original state, including the working directory and staged changes.

#!/bin/sh
function git_snapshot() {
 # Usage: SNAPSHOT=$(git_snapshot <backup_branch> "<commit message>")
 set -e
 # Save the current state.
 BEFORE=$(git rev-parse --abbrev-ref HEAD)
 if [[ "$BEFORE" == 'HEAD' ]]; then
 BEFORE=$(git rev-parse HEAD)
 fi
 (>&2 echo "Starting at $BEFORE.")
 git stash push --include-untracked
 (>&2 echo "Stashed changes ($(git rev-parse stash@{0})).")
 # Commit files to other branch.
 git checkout "1ドル"
 git read-tree -um $BEFORE
 git commit -m "2ドル"
 (>&2 echo "Saved last commit ($(git rev-parse HEAD)).")
 git stash apply --index stash@{0}
 git add -A
 git commit --amend --no-edit
 (>&2 echo "Amended uncommitted changes ($(git rev-parse HEAD)).")
 SNAPSHOT=$(git rev-parse HEAD)
 # Switch back and restore state.
 git checkout $BEFORE
 git stash apply --index stash@{0}
 (>&2 echo "Restored changes.")
 echo $SNAPSHOT
}
asked Aug 3, 2018 at 12:41
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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.

Toby Speight
87.1k14 gold badges104 silver badges322 bronze badges
answered Aug 12, 2018 at 8:13
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.