0

I'm using git stash push -a in a script to save uncommitted changes and then sometime later run git stash pop in the same script to restore the stashed changes. I've run into a problem in which git stash push -a occasionally reports "No local changes to save" and no no stash is created. This causes the subsequent git stash pop to fail with exit code 1. Is there a way I can detect when git stash push -a reports "No local changes to save" so that I know that no stash is created (short of checking the git stash push -a output) and thus not perform the git stash pop?

3
  • Cheeky suggestion: touch $(uuidgen) before stashing :) Commented Jun 27, 2024 at 19:30
  • You can catch the output of git stash and test if it is equal to No local changes to save. In Bash for example, output=$(git stash push -a);if [[ "$output" = "No local changes to save" ]];then no-git-stash-pop;fi. Commented Jun 28, 2024 at 2:18
  • Instead of git stash examine the very changes. Like git update-index -q --refresh && git diff-index --quiet HEAD. Or git ls-files --deleted --modified --others --unmerged --killed --exclude-standard --directory --no-empty-directory Commented Jun 28, 2024 at 8:03

2 Answers 2

1

Botje's "cheeky suggestion" of creating a temporary file so that git stash push -a has at least one file to stash worked for me. Just remember to delete the temporary file after running git stash pop.

Sign up to request clarification or add additional context in comments.

Comments

-2

I would rather suggest checking in those changes as normal, but temporary commits and stop using stash because normal commits are much safer in they do not have dangerous, complicated quirks like stash have.

For your use case, you can save with

git commit -am "AUTOSAVE myscript.sh "$(date +%y-%m-%d_%H-%M-%S)""

and then unsave with

if [[ "$(git log --format=format:%s HEAD^..HEAD)" == "AUTOSAVE myscript.sh"* ]]
then
    git reset HEAD^
fi

2 Comments

I don't see how git reset HEAD^ restores the uncommitted changes; rather, I would think that it deletes them.
Also, I don't think git commit -a commits untracked files (i.e. new files you have not told Git about).

Your Answer

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.