Useful Git Commands
Nov 5, 2022
# Stash Commands
- Stash tracked files with a stash message
1
| git stash save "stash message"
|
- Stash tracked and untracked files (
-u
is shorthand for --include-untracked
) with a stash message
1
| git stash save -u "stash message"
|
1
| git stash show -p stash@{0}
|
- Apply stash by id (Doesn’t delete from stash)
1
| git stash apply stash@{0}
|
- Unstash a single, specific file from a stash
1
| git diff stash@{0}^1 stash@{0} -- <filename>
|
- The
-p
and -u
flag step-by-step walks you through each changed/new file in your repo and asks “Do you want to stash this?”
# Cleaning / Deletion
- Remove a file from source control without deleting it:
1
| git rm --cached mylogfile.log
|
- Remove a directory from source control without deleting it:
1
| git rm --cached mylogfile.log
|
- In case you have not pushed the commit publicly yet, and want to undo it, keeping the changes in your working directory:
1
| git reset HEAD~1 --soft
|
- Dry (
-n
) run for git clean for recursive directory (-d
) deletion of untracked files:
- Delete all untracked files from the repository (ignores files in .gitignore):
- Discard uncommitted, local changes
1
| git branch -d <local-branch>
|
# I committed the deletion and then I did more commits
If you deleted a file, committed, then continued work and did more commits, only to find that deleting the file was a mistake, Git still has you covered! To find the right commit, first check the history for the deleted file:
1
| $ git log -- <filename>
|
You can either work with the last commit that still had the file, or the commit that deleted the file. In the first case, just checkout the file from that commit:
1
| $ git checkout <commit hash> -- <filename>
|
In the second case, checkout the file from one commit before that:
1
| $ git checkout <deletion commit hash>~1 -- <filename>
|
# Merging
1
2
3
4
5
| git checkout main
git pull
git checkout feature
git merge main
git push
|
# Rebasing
- Does an interactive rebase, starting at the most recent commit, and working to the Nth commit from HEAD to produce a squashed commit. The squashed commit replaces each commit starting with HEAD, and ending at N, inclusive.
# Misc. Commands
- Revert singular files back to their state in a previous commit hash
1
| git checkout $COMMIT_SHA -- file1/to/restore file2/to/restore
|
- To view local and remote branches
- To view local and remote branches, and the last commit to each
or
- See number of commits by each author for a branch and their email
- See number of commits since a certain date:
1
| - git shortlog -s -n --since "JAN 1 2022"
|
# Resources