- 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 fetchupdates local reference to theorigin/main;git merge origin/mainmergesorigin/mainintomain.
git pull --rebase=git fetch && git rebase.
- push local branch to the remote and set the upstream
git push --set-upstream origin <new_branch>
we can use
-uinstead of--set-upstream
- 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>
--trackallows to set upstream and sets the same name.
- Modify the last unpushed commit:
git commit --amend
- Discard all uncommited changes:
git restore .
rebase vs merge
These commands integrate changes from one branch into another one in different ways.
git checkout feature
git merge main
mergeadds whole history of commits frommaintofeature.
git checkout feature
git rebase main
This maves the starting commit of
featureon the top ofmainlast 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~3indicates 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 rebasewas 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 mergethere is a commit about merging. - Since
rebasechanges history of commits don't use it on public branches, that are used by other people.
Top comments (0)