= Git Branches = `git(1)` has a concept of '''branches''', which are concurrent versions of a repository. Each branch is an independent collection of commits, can diverge, and can be systemically reconciled as needed. <> ---- == Usage == === Branch === Use the '''`git branch`''' command to interact with branches in a repository. To list available branches, try: {{{ # local branches only git branch # remote branches only git branch --remotes # all branches git branch --all }}} To create a new branch, try: {{{ git branch feature-branch }}} ---- === Checkout and Switch === The traditional command for changing branches is '''`git checkout`'''. This command actually has multiple unrelated functionalities, including restoring files. The new, recommended command is '''`git switch`'''. To demonstrate: {{{ # change branch git switch main # create branch and change to it git switch --create feature-branch # change to previous branch git switch - }}} ---- == Renaming Branches == A local branch can be renamed easily. {{{ git branch --move master dev }}} To rename a remote branch, first follow the above process. Then try: {{{ git push --set-upstream origin dev git push origin --delete master }}} If an error like ` ! [remote rejected] master (deletion of the current branch prohibited)` is thrown, then the remote `HEAD` needs manual intervention. Edit the remote bare repository's `example.git/HEAD` file like: {{{ ref: refs/heads/dev }}} To be clear, valid values for the `example.git/HEAD` file are the branch references found in `example.git/refs/heads/`. ---- == Rebasing Forks == Best practice is to manage local changes in a separate branch. This will make it easier to merge upstream commits while maintaining your own. After fetching or pulling updates, you will be some number of commits behind or ahead (respectively). To throw out local commits, use `git reset --hard origin/master`. Then switch to your local branch and begin '''rebasing''' it. {{{ A---B---C feature-branch / D---E---F---G dev }}} ...to... {{{ A'--B'--C' feature-branch / D---E---F---G dev }}} To execute a rebase, try: {{{ git switch feature-branch git rebase dev }}} With any luck, there will have been no conflicts and you will be all set. If there is an issue with a rebase, try: {{{ git reset --hard $COMMIT_PRIOR_TO_REBASE }}} For example, if the commit prior to a rebase was `HEAD@{2}`, the correction for a bad rebase would be `git reset --hard HEAD@{2}`. ---- == See also == [[https://man.archlinux.org/man/git-branch.1|git-branch(1)]] [[https://man.archlinux.org/man/git-checkout.1|git-checkout(1)]] [[https://man.archlinux.org/man/git-push.1|git-push(1)]] [[https://man.archlinux.org/man/git-rebase.1|git-rebase(1)]] [[https://man.archlinux.org/man/git-reset.1|git-reset(1)]] [[https://man.archlinux.org/man/git-switch.1|git-switch(1)]] ---- CategoryRicottone