Git branches
In this page
- Create and checkout a branch
- List branches
- Copy & Merge
- Delete branches
- Talking to the server
- Swap master branch
1. Create and checkout a branch
The commands below are useful to create, checkout and track branches:
$ git branch <newbranch> # Locally create newbranch $ git checkout <branch> # Locally switch to branch $ git checkout -b <newbranch> # Equivalent to the two above commands ## Checkout remote branch & create local copy $ git checkout -b <branch> origin/<branch> ## Create local branch from remote and set it to be tracked $ git checkout --track -b origin <branch>
2. List branches
To see what branches are available and known locally
$ git branch [-r][-a] # See local, [r]emote, or [a]ll branches (known locally)
To see what branches are available and not known locally
$ git ls-remote <remote-name> # Lists really all remote branches and tags $ git ls-remote <remote-name> \ | grep refs/head/ # Lists really all remote branches (no tags) $ git remote show <remote-name> # Another option
3. Copy & Merge
To copy a version of file in the master to another branch (for instance to update a .gitignore file), do the following:
$ git checkout <branch> # Checkout a local branch $ git checkout master <file> # Copy file from master to branch just checked out
Work on a branch is done and we want to merge into the master branch. That is how:
$ git checkout master # Switch to master branch $ git merge <branch> # Merge branch into master
4. Delete branches
To delete a branch, just do the following:
$ git branch -d <branch> # Delete a local branch $ git push origin :<branch> # Delete a remote branch
5. Talking to the server
To push one branch:
$ git push -u origin <branch> # Push changes in branch to remote repository
To push and pull one branch to the server, it is easier to check it out first. Like this:
$ git checkout <branch> # Switch to branch $ git push; # Push branch to remote $ git pull; # Pull branch from remote
To push all branches to the remote server:
$ git push --all # Push changes in all branches to remote
6. Swap master branch
Swapping the master branch is an obscure task. Supposing that I have a better branch that I want to move into master, which I want to back-up in legacy, this is the best I came up with, so far:
$ git branch -m master legacy # Local: move master to (new) legacy $ git branch -m better master # Local: move better to (new) master $ git push origin legacy # Remote: create legacy $ git checkout master # Local: switch to (new) master $ git push -f origin master # Remote: (force) delete old / create new master $ git push origin :better # Remote: delete (old copy of) better
The above makes a local mess but the remote seems to be good. Instead of trying --hard resets, and stuff, I prefer to erase the local repository and re-clone it: