book-git-commands/src/branching.md

2.3 KiB

Branching

# Create a new branch.
git branch <branchName>

# Create a new branch at a specific commit, and switch to it.
git checkout -b <branchName> 3f4308df1e0b7f663d851108128e8e53deb1b5fb

# Switch to an existing branch.
git checkout <branchName>
git checkout master

# Checkout and switch to a new branch.
git checkout -b my_new_branch

# Push the new branch to a remote.
git push -u origin my_new_branch

# Alternative way to push a branch to a remote, without permanently setting the upstream.
git push origin my_new_branch

# Checkout a remote branch.
git checkout --track origin/<branchName>

# Merge changes from master into a branch.
git checkout <branchName>
git merge master

# Abort a merge (such as if there's conflicts that need to be resolved differently).
git merge --abort

# Delete a branch.
git branch -d my_new_branch

# Delete a branch on the remote.
git push origin :my_new_branch

# Do a dry run of pruning local branches that no longer exist on a remote.
git remote prune origin --dry-run

# Show all current branches, including remotes.
git show-branch -a --list

# Show all local branches that have been merged into master.
git branch --merged

# Show all local branches that have not been merged into master.
git branch --no-merged

# Show all local branches, sorted by and showing last commit
# https://stackoverflow.com/a/5188364/11912
git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'

# Merge two local branches, without fast-forwarding, with default editor opening to modify the message.
git merge <branchName> --no-ff --edit

# Merge two local branches, without fast-forwarding, and including messages for the last X (20 here) commits.
# According to Linus Torvalds, the better way to do merges.
git merge <branchName> --log=20 --no-ff

# While on a different branch, update the master branch from remote.
# See https://stackoverflow.com/a/42902058/11912
git fetch origin master:master

# Put recent local commits in master into a new branch.
# X is the number of commits to rollback.
git branch <branchName>
git reset --hard HEAD~X
git checkout <branchName>

-- Add a specific commit on top of the current branch.
git cherry-pick a6e1e5ad