---
title: Useful Git Snippets
description: A collection of useful GIT commands and snippets
date: 2021-04-05
tags: git, snippets
source: https://brianchildress.co/blog/useful-git-snippets
---

# Useful Git Snippets

### Here are some useful Git snippets

_Get a count number of the number of branches for a repository._

```sh
git branch | wc -l
```

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

```sh
git branch --all | wc -l
```

_List all branches *not merged* into another branch, i.e. *main*_

```sh
git branch --no-merged main
```

_Determine if a file is being tracked by GIT_

```sh
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, ..._

```sh
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`

```sh
git branch --merged main
```

_Determine what branches have NOT been merged_

```sh
git branch --no-merged main
```

_Merging in another branch with known or suspected conflicts_

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

_Create new branch from previous commit_

```sh
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:

```sh
git diff branch1...branch2
```

_Ignore local file changes_

```sh
git checkout -f
```

_Show current git branch_

```sh
git branch --show-current
```

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

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

_Execute command on all files that have changed_

Example using `yarn`

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

## git stash

_View all stashes_

```sh
git stash list
```

_View files in the latest stash_

```sh
git stash show
```

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

_View files in a specific stash_

```sh
git stash show stash@{n}
```

_Drop last stash_

```sh
git stash drop
```

_Drop specific stash_

```sh
git stash drop stash @{n}
```
