A handful of handy git commands that I don’t use all that often but want to keep track of:
Stashing
Stash a single file
git stash push -m 'message here' -- path/to/file
Drop a specific stash
First figure out the id of the stash you want to drop with git stash list, then issue the following command
git stash drop stash@{n}
Editing Commits
Changing author of already pushed commit
If you need to change the author of a commit that has already pushed, interactive rebase is your friend
First, determine a commit on top of which you want to rebase the commit, or a series of commits. I usually just use the commit that the series of commits is based off of (the root of the branch).
In that case you can just rebase it against that branch (but the hash of a commit before the commit you want to edit works just as well)
git rebase -i main
Your editor will open and you will be able to mark the commit that you want to edit. Change the pick token for that commit to edit and save:quit from your editor. Git will then start rebasing each commit onto the branch/commit you specified and will stop when it reaches the commit you flagged for editing.
At this point, issue the following command (updating the specific email address and author name)
git commit --amend --author="Ryan Chapin <rchapin@nbinteractive.com>" --no-edit
And then issue the commit to continue rebasing the remainder of the commits.
Undo last commit and keep changes
Sometimes you mistakenly commit things that you are not ready to commit. Run the following
git reset --soft HEAD~1
This command will
git reset: move the current branch’s pointer (HEAD) to a specific commit--soft: ensure that the changes from the undone commit are preserved in your staging area and working directory as uncommitted local modifications.HEAD~1: is the reference to the commit just before the current one – the parent of HEAD
gitk
gitk is a GUI git client that has a lot of nice features and is easy to use
See orphaned branches and commits
Run gitk with the following command. Running git log with the same arguments will enable you to see the same commits, but it is much easier to browse and see with gitk.
gitk --all --reflog &
Diffing
Viewing more or less context with git diff
The default number of lines displayed above and below a change is three. To increase or decrease the number of lines displayed in the diff use the -U flag as follows, which will display 10 lines before and after the changes.
git diff -U10
Finding changes to a specific file
git log --follow --patch -- <file-path>
Reverting
When reverting your un-staged changes to your current branch you are checking out the revision from the base branch.
Reverting Changes in an entire subdirectory
git checkout <base-branch> -- path/to/directory
Changing URLs
Changing the remote URL
git remote set-url origin ssh://git@<host>:<path>/REPOSITORY.git