Useful Git Snippets

04-05-2021

Here are some useful Git snippets

Get a count number of the number of branches for a repository.

1
git branch | wc -l

Include the --all flag to get both local and remote branches

1
git branch --all | wc -l

List all branches not merged into another branch, i.e. main

1
git branch --no-merged main

Determine if a file is being tracked by GIT

1
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, …_

1
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

1
git branch --merged main

Determine what branches have NOT been merged

1
git branch --no-merged main

Merging in another branch with known or suspected conflicts

1
git merge <branch> --strategy-option [ours | theirs]

Create new branch from previous commit

1
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:

1
git diff branch1...branch2

Ignore local file changes

1
git checkout -f

Show current git branch

1
git branch --show-current

Show all files that have changed between current local git branch and another branch

1
git diff --name-only --diff-filter=AM <target branch> $(git branch --show-current)

Execute command on all files that have changed

Example using yarn

1
yarn <command> $(git diff --name-only --diff-filter=AM develop $(git branch --show-current))

git stash

View all stashes

1
git stash list

View files in the latest stash

1
git stash show

(To see the content of the file(s) add the -p flag)

View files in a specific stash

1
git stash show stash@{n}

Drop last stash

1
git stash drop

Drop specific stash

1
git stash drop stash @{n}