Git Basics đź’ż
Basic operations
Once
Command | Description |
---|---|
git clone [email protected]:org/repo.git | Get locally the remote repository |
All the time
Command | Description |
---|---|
git pull | Get the latest changes from the remote branch |
git status | Review what is getting added to your next commit |
git add . | Add un-staged files to your next commit |
git commit -m "$message" | Commit all your changes locally |
git push | Push your local commit to the remote branch |
From time to time
Command | Description |
---|---|
git checkout -b "$branch" | Create your own branch to start working on your task |
git checkout $branch | Retrieve existing branch |
git commit --amend --no-edit | You forgot changes to your commit, and want to add them before git push |
git push -f | You amended a commit that was already pushed. You can override the remote commit with a forced push, but use caution - this rewrites history and could cause data loss. Main branches are often protected from forced pushes, so only use this in specific situations. |
Rarely
Command | Description |
---|---|
git reset HEAD~1 | You want to undo your last commit |
git log | Check your local commit history |
git revert $commitHash | You create a “revert commit” removing your changes. You can find the commit hash with git log . |
git fetch | Get the latest remote repository changes (branches, tags, …) |
git stash | Put uncommitted changes on the shelf to work on something else or apply it to a different branch |
git stash apply | Take back from the shelf your “saved” changes |
git remote -v | Check where is located your remote repository (fetch/push) |
git remote add origin [email protected]:org/repo.git | Add remote repository - you probably did right before a git remote rm origin . |
git reset --hard origin/main | Forceful reset of your local main branch to realign to the remote state |
git rebase -i HEAD~3 | Interactive way through rebase to rewrite your 3 last commits git history (e.g. to squash commits) |
Git merge vs rebase
Eventually, you will want to incorporate your work into the main codebase that your team shares. Before opening a pull or merge request, to prevent any merge conflicts, you should update your own branch with the latest changes from the main branch:
-
git pull origin main
to fetch the latest changes from the main branch -
Choose between two merge strategies based on your team’s preferences:
git merge main
: This applies your changes and merges them with main, creating an extra merge commit. This is the easiest and preserves history but creates extraneous merge commits in your git history.git rebase main
: This rewrites history by applying each of your commits on top of main. Fix any conflicts, then force push (git push -f
). This makes for a cleaner history but be careful - rewriting history can cause data loss if not done carefully.
Last updated on