bash functions & git - how to wipe out changes made to a specific file

2019-04-07

 | 

~3 min read

 | 

439 words

I find myself writing the following command multiple times daily.

git stash push pacakage-lock.json
git stash drop 0

I had been reading a little about bash functions and wanted to see if I couldn’t automate the process.1

There are two files in particular that I was running these commands for due to our build process: pacakge.json and package-lock.json.

My first solution was a hard coded version called cpkg. I saved the function my ~/.zshrc for easy access.

#cpkg = "clear changes to pacakge"
cpkg() {
  git stash push package-lock.json;
  git stash drop 0;
  git stash push package.json;
  git stash drop 0;
}

This function achieves my goal. It wipes out changes to the package.json and package-lock.json.

Still, I wanted to challenge myself to see if I could add some dynamism. Maybe I wouldn’t want to clear my package, but drop changes from a different file.

This required a function that accepted arguments.

Parameters And Bash Functions

The first place I looked, of course, was Stackoverflow.2 This conversation was a good introduction of how functions pass parameters.

In my case, I only needed to handle a single parameter - so order wasn’t important and I could use the $1 without any type checking.

What I came up with was:

#gsdf = "git stash drop file"
gsdf() {
  git stash push $1;
  git stash drop 0;
}

It’s simple, but it does work as expected.

If I run gsdf package.json the file will be added to the stash (if there have been changes) and then dropped - letting me move on in peace.

This works by assigning package.json to the $1 parameter during execution.

The next steps would be to handle multiple arguments, so I could pass multiple files at once.

Caveats

This will not affect untracked or ignored files. It will only wipe out changes to files that have been previously tracked or committed.

The reason is that git stash does not stash untracked or ignored files by default.3

Final Thoughts

Is this the best way to achieve my goal? Probably not, but it’s been w working for me and I understand it. If you can point me to a more common pattern with git for this, I’m all ears.

I’d also be very interested if someone knows a good way of handling an unknown number of arguments to create a loop of repeating this process for each file passed into the gsdf function.

Footnotes


Related Posts
  • Git Checkout Partial Targets
  • Git - Renaming A Branch: Locally & Remotely
  • Git Restore vs Reset vs Revert: The Basics
  • Zsh: Calling Functions Within Functions


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!