cheatsheets/git-branch.md

103 lines
1.6 KiB
Markdown
Raw Permalink Normal View History

2014-09-11 14:25:43 +00:00
---
title: Git branches
2015-11-24 04:30:17 +00:00
category: Git
2020-07-04 13:33:09 +00:00
updated: 2020-02-13
2014-09-11 14:25:43 +00:00
---
2017-09-20 14:04:14 +00:00
## Working with branches
{: .-three-column}
2014-09-11 14:25:43 +00:00
2017-09-20 14:04:14 +00:00
### Creating
2014-09-11 14:25:43 +00:00
2017-09-20 14:04:14 +00:00
```bash
git checkout -b $branchname
git push origin $branchname --set-upstream
```
2014-09-11 14:25:43 +00:00
2017-09-20 14:04:14 +00:00
Creates a new branch locally then pushes it.
2014-09-11 14:25:43 +00:00
2017-09-20 14:04:14 +00:00
### Getting from remote
2014-09-11 14:25:43 +00:00
2017-09-20 14:04:14 +00:00
```bash
git fetch origin
git checkout --track origin/$branchname
```
Gets a branch in a remote.
### Delete local remote-tracking branches
```bash
git remote prune origin
```
Deletes `origin/*` branches in your local copy. Doesn't affect the remote.
### List existing branches
```bash
git branch --list
```
Existing branches are listed. Current branch will be highlighted with an asterisk.
2017-09-20 14:04:14 +00:00
### List merged branches
```bash
git branch -a --merged
```
List outdated branches that have been merged into the current one.
### Delete a local branch
2020-01-20 05:13:57 +00:00
```bash
git branch -d $branchname
```
2020-01-20 05:13:57 +00:00
Deletes the branch only if the changes have been pushed and merged with remote.
### Delete branch forcefully
```bash
git branch -D $branchname
```
```bash
git branch -d $branchname
```
> Note: You can also use the -D flag which is synonymous with --delete --force instead of -d. This will delete the branch regardless of its merge status.
> Delete a branch irrespective of its merged status.
2017-09-20 14:04:14 +00:00
### Delete remote branch
```bash
git push origin --delete :$branchname
2017-09-20 14:04:14 +00:00
```
Works for tags, too!
### Get current sha1
```bash
git show-ref HEAD -s
```
2020-01-10 02:45:50 +00:00
### Reset branch and remove all changes
```bash
git reset --hard
```
2020-01-20 05:15:24 +00:00
### Undo commits to a specific commit
2020-01-10 02:45:50 +00:00
```bash
2020-01-20 05:15:41 +00:00
git reset --hard $commit_id
2020-01-20 05:15:24 +00:00
# Now push safely to your branch
git push --force-with-lease
# Or push brutally to your branch
2020-01-10 02:45:50 +00:00
git push --force
```