This cheat sheet provides an overview of essential Git commands categorized into Beginner, Intermediate/Advanced, and Expert levels. Additionally, it highlights the Most Used Git Commands for quick reference, common issues with solutions, workflow instructions, and necessary prerequisites.
Before starting, ensure you have the following installed and configured:
- Git: Download and install from git-scm.com
- Visual Studio Code: Download from code.visualstudio.com
- Configure Git (once installed):
git config --global user.name "Your Name" git config --global user.email "your.email@example.com"
Optional:
- Set up SSH keys or credential helper for smoother authentication with remote repositories.
| Command | Description | Example |
|---|---|---|
git init |
Initialize a new Git repository | git init |
git clone |
Clone an existing repository | git clone https://github.com/user/repo.git |
git status |
Check the status of your working directory | git status |
git add |
Stage changes for commit | git add filename or git add . or git add *.py |
git commit |
Commit staged changes | git commit -m "Message" |
git branch |
List, create, or delete branches | git branch |
git checkout |
Switch branches or restore files | git checkout branch-name |
git merge |
Merge branches | git merge branch-name |
git pull |
Fetch and merge changes from remote | git pull origin main |
git push |
Push changes to remote | git push origin main |
| Command | Description | Example |
|---|---|---|
git remote |
Manage remote repositories | git remote add origin url |
git fetch |
Download objects and refs from another repository | git fetch |
git rebase |
Reapply commits on top of another base tip | git rebase branch-name |
git stash |
Temporarily store changes | git stash |
git cherry-pick |
Apply specific commits | git cherry-pick commit_hash |
git reset |
Reset current HEAD | git reset --hard commit_hash |
git revert |
Create a new commit that undoes changes | git revert commit_hash |
git log |
Show commit logs | git log or git log --oneline --graph |
git diff |
Show changes between commits, working directory, etc. | git diff |
git tag |
Create, list, or delete tags | git tag v1.0 |
| Command | Description | Example |
|---|---|---|
git filter-branch |
Rewrite history | git filter-branch --tree-filter 'rm -rf tmp/' HEAD |
git cherry |
Find commits not merged upstream | git cherry -v |
git rerere |
Reuse recorded resolution of conflicts | git rerere |
git blame |
Show who last modified each line | git blame filename |
git submodule |
Manage submodules | git submodule update --init |
git gc |
Cleanup unnecessary files and optimize repository | git gc |
git fsck |
Verify the connectivity and validity of objects | git fsck |
| Command | Description |
|---|---|
git clone |
Clone a repository |
git status |
Check current status |
git add |
Stage changes |
git commit |
Commit staged changes |
git push |
Push to remote repository |
git pull |
Pull latest changes from remote |
git branch |
List or create branches |
git checkout |
Switch branches |
git merge |
Merge branches |
Below are typical issues faced when working with Git, along with their solutions:
- Symptom: Git reports conflicts during merge or rebase.
- Solution: Open conflicting files, look for conflict markers (
<<<<<<<,=======,>>>>>>>), and manually resolve the conflicts. After resolving:git add <file> git commit
- Symptom: Committed changes on an unintended branch.
- Solution:
- Switch to the correct branch:
git checkout correct-branch - Cherry-pick commit(s) (if needed):
git cherry-pick <commit-hash> - Optionally, reset the wrong branch:
git checkout wrong-branch git reset --hard HEAD~1
- Switch to the correct branch:
- Symptom: Push fails due to non-fast-forward updates.
- Solution:
- Pull latest changes with rebase:
git pull --rebase - Resolve any conflicts, then push:
git push
- Pull latest changes with rebase:
- Symptom: Files missing after a reset.
- Solution:
- Check reflog to find lost commits/files:
git reflog - Recover the commit:
git checkout -b recovery_branch <commit_hash>
- Check reflog to find lost commits/files:
- Symptom: Files left untracked.
- Solution:
- Check untracked files:
git status - Add files:
git add <file> - Commit:
git commit -m "Add new files"
- Check untracked files:
- Symptom: Git repository becomes slow or bloated.
- Solution:
- Clean up unnecessary files:
git gc --prune=now --aggressive - Remove large unwanted files historically using
filter-branchor tools likebfg-repo-cleaner.
- Clean up unnecessary files:
- Symptom: Conflicts arise when merging branches.
- Solution:
- Resolve conflicts manually by editing files or using
git mergetool. - Carefully rebase or merge branches, considering the history and changes to minimize conflicts.
- Resolve conflicts manually by editing files or using
Open Command Prompt and run the following commands:
git clone https://github.com/username/repositoryname
ls
cd .\repositoryname\
git remote -v
code .
- This clones the repository, opens the folder in Visual Studio Code, and prepares it for work.
After editing your files, commit and push your updates:
git add .
git commit -m "updated work"
git push origin main
If you haven't made local changes yet, you don’t need to git add or git commit before git pull.
If you’ve already cloned the repository and want to sync the latest changes, follow these commands:
git pull origin main
git add .
git commit -m "your message"
git push origin main
- This stages your changes, commits, and pulls the latest updates from the remote repository to keep your local copy current.
It's also a good idea to occasionally fetch and review the log:
git fetch
git log --oneline --graph --all
to understand the commit history.
If you've already cloned the repo and want to add a file:
git status
git add filename.ext
git commit -m "Add: description of the new file"
git pull origin main --rebase
git push origin main
Replace filename.ext with your actual filename and description.
When running:
git pushGit displays:
fatal: The current branch main has no upstream branch.This happens because the local main branch is not linked to a remote branch on GitHub.
git remote -vIf you get something like:
origin https://github.com/USERNAME/Git_and_Github.git (fetch)
origin https://github.com/USERNAME/Git_and_Github.git (push)then your remote already exists.
If nothing appears, then you haven't added a remote yet.
Set the upstream branch and push:
git push -u origin mainor
git push --set-upstream origin mainThis command does two things:
- pushes your code
- connects your local main branch to GitHub
Add the GitHub repository:
git remote add origin https://github.com/<username>/<repository>.gitThen push:
git push -u origin mainAfter the upstream branch is configured, future pushes only require:
git pushIf
git push -u origin mainfails
Run these commands and send me the output:
git remote -v
git branch -vv
git remote show originRunning the following command:
git pullproduced the error:
fatal: couldn't find remote ref refs/heads/django_templateAlthough the repository's default branch was main, Git was still trying to pull from a deleted or non-existent remote branch named django_template.
The local branch was configured to track the remote branch:
origin/django_templateHowever, that branch had already been removed from the remote repository. Because the local Git configuration still referenced it, every git pull attempted to fetch a branch that no longer existed.
git remote prune originThis removes references to remote branches that have been deleted.
git fetch origin mainThis updates the local repository with the latest information from the main branch.
git pull origin mainThis successfully downloads and merges the latest changes from the remote main branch.
The repository was updated successfully using a fast-forward merge, and all latest changes from the remote main branch were downloaded.
If git pull continues to look for the deleted branch, update the upstream branch:
git branch --unset-upstream
git branch --set-upstream-to=origin/main <local-branch-name>Replace <local-branch-name> with your current local branch name (for example, main or master).
You can check your current branch with:
git branchYou want to create a new branch from the main branch, work on a new feature independently, and push the branch to GitHub without affecting the main branch.
git branchExpected output:
* main
If you are not on main, switch to it:
git switch mainReplace api with your preferred branch name.
git switch -c apiVerify the current branch:
git branchExpected output:
* api
mainModify, add, or delete files as needed.
Check the current status:
git statusgit add .
git commit -m "feat(api): add REST API implementation"Since the branch does not yet exist on the remote repository:
git push -u origin apiThe -u option sets the upstream branch, allowing future pushes with:
git pushgit branch -aExpected output:
* api
main
remotes/origin/api
remotes/origin/mainSwitch to the main branch:
git switch mainSwitch back to the api branch:
git switch apimain
│
│
├───────────────●───────────────●
\
\
api ●──────────────●mainremains stable.apiis used for feature development.- Changes can later be merged into
mainusing a pull request orgit merge.
A new feature branch is created, development is isolated from the main branch, and the branch is successfully pushed to GitHub with upstream tracking configured. This workflow is the standard practice for collaborative Git development.
While pushing commits to GitHub, the following error appears:
remote: fatal error in commit_refs
To https://github.com/your-username/your-repository.git
! [remote rejected] main -> main (failure)
error: failed to push some refsThis error means your local Git commands completed successfully, but the remote repository rejected the push. The issue is typically related to the remote repository or requires further investigation to determine the exact cause.
Follow the steps below to diagnose and resolve the issue.
Verify the current status of your local repository.
git statusThen inspect the most recent commits.
git log --oneline --graph --decorate -5These commands help confirm that your working tree is clean and that the expected commits exist locally.
Check that your repository is connected to the correct remote.
git remote -vEnsure that both the fetch and push URLs point to the intended GitHub repository.
Fetch the latest changes from GitHub.
git fetch originCompare your local branch with the remote branch.
View commits that exist locally but have not been pushed:
git log --oneline origin/main..HEADView commits that exist on the remote but not locally:
git log --oneline HEAD..origin/mainThis helps determine whether your local and remote branches have diverged.
Sometimes the error is caused by a temporary issue on GitHub.
Retry the push:
git pushIf the push succeeds, no further action is required.
If the error persists, continue to the next step.
Collect more detailed information about the push operation.
git push --verbose- The command
git push --verbose(or its shorthandgit push -v) forces Git to run the upload process verbosely, outputting extra details about the connection and transmission. - According to the official Git documentation, its main effect is showing the status of up-to-date references, which Git normally hides to keep terminal logs clean.
Key Features of Verbose Mode
- Lists all branches: It prints confirmation lines for every branch evaluated, even those already up to date on the remote server.
- Server details: It displays the specific remote repository URL and communication steps used during data transfer.
- Troubleshooting aid: It helps diagnose frozen or stuck transfers by displaying explicit progress milestones.
Or enable Git tracing.
GIT_TRACE=1 git push$env:GIT_TRACE=1
git pushThe additional output can help identify the exact reason for the failure.
GitHub may occasionally experience temporary internal errors that reject pushes.
In this case:
- Wait a few minutes.
- Retry the push.
- Check GitHub's service status if the problem continues.
If the target branch is protected, GitHub usually returns an error similar to:
protected branch hook declined
If you do not see this message, branch protection is unlikely to be the cause.
Large files, Git LFS configuration, or certain repository policies may prevent a successful push.
Although renaming files generally does not cause this issue, repository rules or storage limitations could contribute to the failure.
Run the following commands and review their outputs.
git statusgit log --oneline --graph --decorate -5git remote -vgit fetch origingit push --verboseThese commands provide enough information to determine whether the issue originates from the local repository, the remote repository, or GitHub itself.
Do not use the following commands unless you fully understand their effects.
git push --forcegit reset --hardBoth commands can overwrite history or permanently discard local changes.
If you encounter the remote: fatal error in commit_refs error:
- Check the repository status.
- Verify the remote configuration.
- Fetch and compare the local and remote branches.
- Retry the push.
- Collect verbose output if the problem persists.
- Review possible causes such as temporary GitHub issues, branch protection, or repository restrictions.
Following these steps will help you identify the root cause before applying any potentially destructive Git commands.
This guide promotes the effective, responsible, and ethical use of Git and GitHub.
Misuse, including unauthorized data access, modification, or damage, is strictly prohibited. The author is not responsible for any consequences arising from the misuse of these instructions.
All content, credits, and intellectual property belong to their respective owners. This guide is intended for educational and personal use only, supporting best practices in version control.
Happy Git-ing! Happy coding!
