- You have created a repository on github and want to work on the local machine:
git clone <repository_url HTTPS or SSH>
- Show the url that Git has stored:
git remote -v
origin is the default name Git gives to the url that Git cloned from
- Create a branch and switch to it:
git checkout -b <new_branch>
- Get the latest update from the main branch:
git checkout main
git pull origin main
git checkout <new_branch>
git merge main
git pull
=git fetch && git merge
.git fetch
updates local reference to theorigin/main
;git merge origin/main
mergesorigin/main
intomain
.
git pull --rebase
=git fetch && git rebase
.
- push local branch to the remote and set the upstream
git push --set-upstream origin <new_branch>
- Check what upstream is assigned to the local branch:
git branch -vv
- Delete remote branch that is upstream:
git push origin :<new_branch>
notice the colon!
- Delete branch locally:
git checkout main
git branch -d <new_branch>
- Delete local references to deleted branches:
git remote prune origin
- Remove git commit which has not been pushed:
git reset HEAD~1
- Create local branch from an existing remote branch:
git checkout --track origin/<REMOTE_BRANCH_NAME>
--track
allows to set upstream and sets the same name.
- Modify the last unpushed commit:
git commit --amend
rebase vs merge
These commands integrate changes from one branch into another one in different ways.
git checkout feature
git merge main
merge
adds whole history of commits frommain
tofeature
.
git checkout feature
git rebase main
This maves the starting commit of
feature
on the top ofmain
last commit. If we check history of commits now, hashes of commits will be different from the original ones.
squash merge
We can squash all commits from the feature branch into 1 commit:
git checkout main
git merge --squash feature
git commit
Interactive rebase
git checkout feature
git rebase -i main
Since rebase creates new commits, we can change them to clean up a messsy history. It will open a list of the commits that are about to be moved:
pick 33d5b7a Message for commit #1
fixup 9480b3d Message for commit #2
pick 5c67e61 Message for commit #3
- fixup unites #2 commit with #1 commit with the message of #1 commit.
Cleanup
We don't necessarily need another branch to use interactive rebase:
git checkout feature
git rebase -i HEAD~3
HEAD~3
indicates the last 3 commits.
Conflicts with rebase
In case of the conflicts. We have three options:
-
git rebase --abort
- undo the rebase. The branche's state returns to the state beforegit rebase
was called. -
git rebase --skip
- skip the commit. The changes made in the problematic commit won't be included. - Resolve convlicts manually and run
git rebase --continue
Important notes of rebase
- Much cleaner commit history. In case of
git merge
there is a commit about merging. - Since
rebase
changes history of commits don't use it on public branches, that are used by other people.
Top comments (0)