Here are some useful Git snippets
Get a count number of the number of branches for a repository.
git branch | wc -l
Include the --all
flag to get both local and remote branches
git branch --all | wc -l
List all branches not merged into another branch, i.e. main
git branch --no-merged main
Determine if a file is being tracked by GIT
git ls-files --error-unmatch <file name>
If a file s not tracked by GIT currently the command will exist with an error.
Delete multiple branches, example use case: delete all branches like: PR_123, PR_124, …
git branch -D `git branch | grep -E '^PR_*'`
NOTE The -D flag will force a delete, even if unmerged changes are present
Determine if a branch has been merged
From the branch you’re interested in, eg: git checkout develop
git branch --merged main
Determine what branches have NOT been merged
git branch --no-merged main
Merging in another branch with known or suspected conflicts
git merge <branch> --strategy-option [ours | theirs]
Create new branch from previous commit
git checkout -b <new branch name> <sha of commit>
Compare two git branches
If you need to determine the differences between 2 branches, use the ...
syntax:
git diff branch1...branch2
Ignore local file changes
git checkout -f
Show current git branch
git branch --show-current
Show all files that have changed between current local git branch and another branch
git diff --name-only --diff-filter=AM <target branch> $(git branch --show-current)
Execute command on all files that have changed
Example using yarn
yarn <command> $(git diff --name-only --diff-filter=AM develop $(git branch --show-current))
git stash
View all stashes
git stash list
View files in the latest stash
git stash show
(To see the content of the file(s) add the -p
flag)
View files in a specific stash
git stash show stash@{n}
Drop last stash
git stash drop
Drop specific stash
git stash drop stash @{n}