Essential Git Commands Every Developer Should Know


Git is a distributed version control system used to track changes, coordinate parallel development, and preserve a project's history. Whether you build web applications, APIs, data pipelines, command-line tools, or mobile apps, Git helps you understand what changed, review work before sharing it, and recover from mistakes. This guide focuses on practical commands that you can use from a terminal on Linux, macOS, or Windows.
The goal is not to memorize every option. It is to understand the everyday workflow: inspect a repository, stage a deliberate set of changes, create useful commits, work on branches, synchronize with a remote, review differences, and recover safely. Commands that rewrite history or discard changes deserve special care; examples below explain the risks before recommending them.
Git is distributed: a local clone contains repository data and history, so you can commit, inspect, compare, and branch without a network connection. A hosting service such as GitHub or GitLab adds collaboration features, but Git itself is the version control program.
Three areas define the everyday workflow:
The flow is:
Edit files -> Working tree -> git add -> Staging area
-> git commit -> Local repository -> git push -> Remote
The staging area is important because it lets you choose exactly what a commit contains. You might edit three files but stage only one bug fix, leaving the other work for a separate commit. This creates focused changes that are easier to review, revert, and understand.
Git and GitHub are not interchangeable terms. Git is the version control system; GitHub is one service for hosting Git repositories and reviewing contributions. You can use Git with GitLab, Bitbucket, self-hosted servers, or entirely offline.
Check whether Git is installed:
git --version
If it is missing, install it using the package manager for your operating system. On Ubuntu or Debian:
sudo apt update
sudo apt install git
On Fedora:
sudo dnf install git
On Arch Linux:
sudo pacman -S git
On macOS, Apple's command-line tools can provide Git with xcode-select --install; Homebrew is another common option. On Windows, install Git for Windows and use Git Bash, PowerShell, or Windows Terminal.
Configure the identity recorded in new commits:
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
Use an address associated with your hosting account if you want commits attributed to it. If you do not want to publish a personal email address, check whether your provider supplies a private noreply address.
The --global option applies to your user account on the machine. To use a different identity in one repository, run git config user.name and git config user.email from inside that repository without --global. Inspect settings with:
git config --list
git config --show-origin --list
Git reads settings from multiple levels, including system, global, and repository-local configuration. More specific settings override less specific ones.
A useful optional setting for new repositories is:
git config --global init.defaultBranch main
This sets the initial branch name created by git init. Projects may use another default branch name, so always check the repository rather than assuming it is main.
To start version control for a new project:
mkdir inventory-api
cd inventory-api
git init
Git creates a hidden .git directory that stores repository data. Your source files remain in the working directory. Run git status to confirm the repository was initialized.
To download an existing repository:
git clone https://github.com/owner/project.git
cd project
Cloning downloads the repository and its history, configures a remote commonly named origin, and checks out the default branch. You can choose a different local directory:
git clone https://github.com/owner/project.git inventory-service
Private repositories require authentication. HTTPS commonly uses a credential manager or provider-supported token; SSH uses a configured key. Never place a password or access token directly in a command that may be saved in shell history, and never commit credentials into the repository.
After cloning, verify the directory, branch, and remote:
pwd
git status
git branch --show-current
git remote -v
These checks are simple but prevent working in the wrong repository or pushing to an unintended remote.
The command to run regularly is:
git status
It shows the current branch, staged changes, unstaged changes, and untracked files. For a compact view:
git status --short
Common status markers include M for modified, A for added, D for deleted, and ?? for untracked files. The two columns indicate whether a change is in the index or working tree.
To inspect changes that are not staged:
git diff
To inspect changes already staged for the next commit:
git diff --staged
To list tracked files:
git ls-files
A .gitignore file defines patterns for untracked files Git should normally ignore. A typical application might include:
.env
.env.*
!.env.example
node_modules/
.venv/
__pycache__/
dist/
build/
*.log
.DS_Store
Adapt the rules to the project. Do not ignore files the application needs to build or run. Also remember that adding a path to .gitignore does not stop tracking it if it was already committed. To remove a file from the index but keep the local copy, use git rm --cached path/to/file and commit that change.
To discover why a file is ignored:
git check-ignore -v path/to/file
This reports the matching ignore rule and where it was defined.
Use git add to move selected changes into the staging area:
git add README.md
git add src/
git add -A
The first stages one file, the second stages a directory, and -A stages additions, modifications, and deletions throughout the repository. git add . stages changes under the current directory. Review the result with git status before committing.
For more precise control, use interactive patch mode:
git add -p
Git presents change hunks so you can stage only the relevant pieces. This is valuable when one file contains unrelated edits and you want each commit to represent one logical change.
Create a commit:
git commit -m "Add request validation to inventory endpoint"
A useful commit message explains the change. "Fix token expiry validation" is more informative than "Updated code." Many teams use an imperative style such as Add, Fix, or Remove; consistency with the project's convention is the priority.
Before committing, inspect the staged patch:
git diff --staged
A commit records the staged snapshot, not every edit in the working directory. If you forgot a small change in the latest local commit, stage it and amend:
git add path/to/file
git commit --amend
Amending replaces the previous commit with a new commit identifier. It is appropriate before sharing the commit. Avoid amending work that teammates may already have pulled unless you coordinate with them.
Use git log to inspect the project's history:
git log
git log --oneline
git log --oneline --graph --decorate --all
git log -5
The graph view helps visualize branches and merges. To inspect one commit and its patch:
git show a1b2c3d
git show --stat a1b2c3d
To search commit messages:
git log --oneline --grep="authentication"
To see commits that changed a specific file:
git log --oneline -- src/auth/login.ts
git blame displays the commit and author associated with each line:
git blame src/auth/login.ts
Use blame as a history investigation tool, not as a way to assign fault. Follow interesting lines into their commits with git show to understand the larger change.
The git diff command compares versions of files:
git diff
git diff --staged
git diff main...HEAD
git diff a1b2c3d..d4e5f6a
git diff -- src/auth/login.ts
The three-dot form compares the current branch with the common ancestor of main and HEAD, which is useful for reviewing the work introduced by a topic branch. The two-dot form compares the specified commit trees. Always inspect the patch rather than assuming that a command's successful exit means the change is correct.
A branch is a movable reference to a commit. It allows work to proceed independently without changing the shared baseline.
List local branches:
git branch
git branch -a
git branch -vv
Create a branch:
git branch feature/profile-page
Switch to it:
git switch feature/profile-page
Or create and switch in one command:
git switch -c feature/profile-page
Older repositories may use git checkout branch-name and git checkout -b branch-name. Those commands remain supported, but modern Git also provides git switch for branch navigation and git restore for restoring files. This separation makes the intent clearer.
Before switching, check git status. Git may carry non-conflicting edits across a branch switch, but it can refuse if doing so would overwrite work. Commit or stash changes when appropriate.
Delete a branch after its work has been integrated:
git branch -d feature/profile-page
The -d option refuses to delete a branch Git considers unmerged. The uppercase -D forces deletion and can discard the only branch reference to unmerged work, so use it only after confirming the work is no longer needed or is safely preserved.
Rename the current branch:
git branch -m feature/profile-settings
A common team pattern is to create a short-lived branch from the agreed base branch, make focused commits, push it, and open a pull request. The base branch may be main, develop, or another name chosen by the project.
Merge integrates another branch into the branch currently checked out:
git switch main
git merge feature/profile-page
If the current branch has not diverged, Git may perform a fast-forward merge by moving the branch pointer. If both branches contain unique commits, Git may create a merge commit.
To always create a merge commit when possible:
git merge --no-ff feature/profile-page
To refuse an integration that cannot be fast-forwarded:
git merge --ff-only feature/profile-page
Rebase replays your branch's commits on top of another base:
git fetch origin
git switch feature/profile-page
git rebase origin/main
Rebase can produce a linear history, but it changes commit identifiers for replayed commits. Rebase your own unpublished topic branch when your team allows it; do not casually rewrite commits that others may already have based work on. Coordinate before rebasing a shared branch.
Neither merge nor rebase is universally better. Merge preserves the branch integration history and is often appropriate for shared work. Rebase can make a personal topic branch easier to review. Follow the project's contribution policy and understand whether an operation rewrites published history.
A remote is a named connection to another repository. List configured remotes and URLs:
git remote
git remote -v
Add a remote:
git remote add origin https://github.com/owner/project.git
Change its URL:
git remote set-url origin [email protected]:owner/project.git
Remove the local remote configuration:
git remote remove origin
Removing a remote does not delete the remote repository. It only removes the local name and URL.
When contributing to a fork, origin commonly refers to your fork and upstream to the original project:
git remote add upstream https://github.com/original-owner/project.git
git remote -v
These names are conventions rather than special keywords.
Fetch downloads new objects and remote-tracking references without integrating them into your current branch:
git fetch origin
After fetching, inspect incoming commits:
git log --oneline HEAD..origin/main
git diff HEAD...origin/main
Pull fetches and then integrates remote changes. The integration behavior depends on configuration and options. A conservative option is:
git pull --ff-only origin main
This refuses to create a merge commit when the local and remote branches have diverged. If your team prefers rebasing local commits:
git pull --rebase origin main
Use the strategy agreed by the project. If Git reports divergent branches, inspect the history and choose intentionally instead of repeatedly retrying.
Push your branch to the remote:
git push origin feature/profile-page
For the first push, set the upstream tracking branch:
git push -u origin feature/profile-page
After tracking is configured, Git can often infer the remote branch for future push and pull operations. Check tracking information with git branch -vv.
Avoid pushing unfinished work directly to a protected shared branch. A safer collaborative flow is to push a topic branch, open a pull request, run automated checks, request review, and merge after approval.
If you intentionally rebased your own remote branch and need to update it, use --force-with-lease only when the repository's rules allow it:
git push --force-with-lease origin feature/profile-page
This checks that the remote is still at the value your local repository expects. It is safer than --force, but it can still overwrite another person's work if used without care. Fetch first and coordinate with collaborators.
When you need to switch branches before your current work is ready to commit, stash it:
git stash push -m "WIP: profile validation"
git stash list
git stash show -p stash@{0}
Restore the latest stash and remove it from the stash list:
git stash pop
Apply a stash without removing it:
git stash apply stash@{0}
To include untracked files, use git stash push --include-untracked. Stashes are local and are not a backup or shared collaboration mechanism. Reapplying a stash can cause conflicts, so check git status afterward.
Git worktrees let you check out more than one branch into separate directories while sharing the same repository data:
git worktree add ../project-hotfix hotfix/login-error
git worktree list
Create a new branch and worktree together:
git worktree add -b feature/dashboard ../project-dashboard main
This is useful when you need to test a hotfix without interrupting a feature branch in your main working directory. Remove a worktree through Git when finished:
git worktree remove ../project-hotfix
If you deleted a worktree directory outside Git, git worktree prune can clean stale records after you verify the directory is truly gone.
Git has several commands that appear to undo work, but they operate at different stages.
Unstage a file while keeping its edits:
git restore --staged README.md
Discard unstaged edits in a file and restore it from the index:
git restore README.md
The second command discards local edits to that file. Inspect the diff first and make sure you do not need those changes. To restore a file from a particular commit:
git restore --source=a1b2c3d -- README.md
git reset moves the current branch reference and can also change the index and working tree:
git reset --soft HEAD~1
git reset --mixed HEAD~1
git reset --hard HEAD~1
Treat git reset --hard as destructive. Check git status and consider creating a backup branch or saving a patch before using it. git clean is a separate command that can remove untracked files; preview what it would delete with git clean -n before considering a real cleanup.
If a commit has already been shared, git revert is often safer:
git revert a1b2c3d
It creates a new commit that reverses the selected commit while preserving existing history. Reverting a merge commit requires choosing a mainline parent with -m, so inspect the merge and understand the result first.
In short: restore changes files or staging, reset moves branch history and may reset the index or working tree, and revert records a new commit that reverses an earlier one. Choose based on whether the work is committed and whether other people may depend on it.
A conflict occurs when Git cannot combine changes automatically. It often happens when two branches edit overlapping lines, but file renames and delete-versus-edit changes can also conflict.
Start with:
git status
Git identifies the files that need attention. Open each file and look for markers:
<<<<<<< HEAD
Current branch version
=======
Incoming branch version
>>>>>>> feature/profile-page
Edit the file so it contains the intended final result, then remove all conflict markers. Do not choose one side blindly; understand both changes and combine them when necessary.
Stage the resolved files:
git add src/profile.ts
git status
For a merge, finish with git commit. For a rebase, continue with:
git rebase --continue
If you decide not to continue, use the operation-specific abort command:
git merge --abort
git rebase --abort
Use the command that matches the operation in progress. A visual merge tool can help with complicated files:
git mergetool
After resolving conflicts, inspect the final diff and run the relevant tests. A conflict-free merge does not guarantee that the combined application behaves correctly.
Tags mark important commits, commonly releases. Create an annotated release tag:
git tag -a v1.0.0 -m "Release version 1.0.0"
git tag
git show v1.0.0
Push a particular tag:
git push origin v1.0.0
Or push all local tags:
git push origin --tags
Cherry-pick applies the changes from one commit to your current branch:
git switch release/1.x
git cherry-pick a1b2c3d
This is useful for backporting a focused fix without merging an entire feature branch. If conflicts occur, resolve them and run git cherry-pick --continue, or cancel with git cherry-pick --abort.
git bisect uses binary search to locate the commit that introduced a regression:
git bisect start
git bisect bad
git bisect good v1.2.0
Git checks out a commit between the known good and bad points. Run a repeatable test, then mark the result:
git bisect good
# or
git bisect bad
Git narrows the range until it identifies the first bad commit. Finish and return to your original branch with:
git bisect reset
A reliable test is essential. If a commit cannot be tested, git bisect skip can exclude it, but skipping commits may make the result less precise.
The reflog records recent movements of local references such as HEAD. It can help recover work after a reset, checkout, or accidental branch deletion:
git reflog
Find the relevant commit, inspect it, and create a recovery branch:
git show a1b2c3d
git switch -c recovery/restore-work a1b2c3d
Reflog entries are local and expire according to repository maintenance settings. They are a recovery aid, not a permanent archive, so recover important work promptly.
Prevent credential leaks by keeping API keys, passwords, private certificates, and environment-specific secrets out of source control. Store them in environment variables or a secrets manager. Commit a safe .env.example file with placeholder values, and add real environment files to .gitignore before staging.
If a credential is committed or pushed, deleting the file in a later commit does not make the exposed value safe. Revoke or rotate it immediately, assess what it could access, and review relevant logs. Then follow your hosting provider's guidance for removing the secret from repository history if necessary.
git filter-repo is a modern external tool often used to remove sensitive files or replace exposed text throughout repository history. It is not built into Git and may need separate installation. Rewriting history changes commit IDs and requires coordinated cleanup of affected clones, branches, and tags. Do not rewrite a shared repository without agreement from its maintainers. History cleanup does not replace credential rotation.
Enable secret scanning and push protection where your hosting provider supports them. These controls can catch some accidental exposures, but they do not replace sound secret management.
Aliases create shortcuts for commands you use frequently:
git config --global alias.st status
git config --global alias.sw switch
git config --global alias.br branch
git config --global alias.lg "log --oneline --graph --decorate --all"
Then run git st, git sw main, or git lg. Aliases are personal configuration and are not automatically shared with teammates. Keep automation scripts explicit and predictable rather than relying on aliases that may not exist on another machine.
Inspect configured aliases:
git config --get-regexp '^alias\.'
The following sequence demonstrates a practical workflow in a project whose shared branch is main. Adapt branch names and integration rules to the repository.
First, synchronize the base branch:
git switch main
git fetch origin
git pull --ff-only origin main
Create a branch for one task:
git switch -c feature/contact-form-validation
Make the change, inspect the working tree, and review the patch:
git status
git diff
Run the project's tests and checks. Stage only the files related to the feature:
git add src/contact-form.ts tests/contact-form.test.ts
git diff --staged
Commit the reviewed work:
git commit -m "Add contact form validation"
Before sharing, fetch the latest remote information and update your branch according to the team's policy. If rebasing personal topic branches is allowed:
git fetch origin
git rebase origin/main
Resolve any conflicts, rerun tests, and push:
git push -u origin feature/contact-form-validation
Open a pull request that explains the problem, the implementation, and the checks performed. Keep it focused, respond to review comments, and update the same branch when appropriate. After approval and merge, update your local main branch and remove the local feature branch:
git switch main
git pull --ff-only origin main
git branch -d feature/contact-form-validation
If the hosting platform has not automatically deleted the remote topic branch, remove it with git push origin --delete feature/contact-form-validation. Follow the repository's branch protection and release policies; not every team uses the same workflow.
'Not a git repository'. You are outside the project directory or the directory has not been initialized. Use pwd and ls to check your location, then cd into the repository. Run git init only when you intend to create a new repository.
'Author identity unknown'. Configure user.name and user.email. Use --global for your normal identity or a repository-local setting for a project-specific identity.
Push rejected because the remote contains work you do not have. Do not immediately force push. Fetch, inspect the incoming commits, and integrate them using the team's merge or rebase policy before pushing again.
The branch has no upstream. Set tracking during the first push with git push -u origin branch-name. Confirm the tracking relationship with git branch -vv.
A file is missing from the commit. Check git status. If the commit is local and the file belongs in it, stage the file and amend. If the commit is already shared, a new commit is often clearer and safer.
A file is ignored unexpectedly. Run git check-ignore -v path/to/file and inspect the matching rule. Check both project-level and global ignore settings.
A tracked file should now be ignored. Add the ignore rule, then use git rm --cached path/to/file. This removes it from the index while keeping the local file.
A merge or rebase is in progress. Run git status to identify the operation. Resolve conflicts and continue, or use the matching abort command if you need to cancel.
You deleted a branch by mistake. Inspect git reflog for the commit at the branch tip and recreate it with git switch -c branch-name commit-id while the commit is still available.
A branch switch would overwrite local changes. Inspect the working tree and decide whether to commit, stash, or safely move the edits. Do not run reset --hard just to bypass the warning.
A shared commit introduced a bug. Use git revert to create a corrective commit that preserves history. Use reset only when you understand the impact on every branch and collaborator that may depend on the commit.
| Task | Command |
|---|---|
| Check Git version | git --version |
| Set commit identity | git config --global user.name "Your Name" |
| Initialize repository | git init |
| Clone repository | git clone URL |
| Check working tree | git status |
| Stage one file | git add filename |
| Stage all changes | git add -A |
| Stage selected hunks | git add -p |
| Review unstaged edits | git diff |
| Review staged edits | git diff --staged |
| Commit changes | git commit -m "Message" |
| View compact history | git log --oneline --graph |
| Create and switch branch | git switch -c branch-name |
| Switch branch | git switch branch-name |
| Merge branch | git merge branch-name |
| Rebase on remote main | git rebase origin/main |
| List remotes | git remote -v |
| Fetch remote updates | git fetch origin |
| Pull fast-forward only | git pull --ff-only |
| Push and set upstream | git push -u origin branch-name |
| Stash work | git stash push -m "Description" |
| Restore latest stash | git stash pop |
| Unstage file | git restore --staged filename |
| Restore file edits | git restore filename |
| Revert shared commit | git revert commit-id |
| Inspect reference history | git reflog |
| Create annotated tag | git tag -a v1.0.0 -m "Release" |
| Apply one commit | git cherry-pick commit-id |
| Start regression search | git bisect start |
The cheat sheet is a reminder, not a replacement for understanding the effect of each operation. In particular, restore, reset, clean, rebase, and force push can have significant consequences. Read the built-in help before using an unfamiliar option:
git help <command>
Start by mastering git status, git add, git diff, git commit, git log, git switch, git fetch, git pull, and git push. These commands cover much of the daily workflow for an individual developer or a member of a small team.
As your projects become more collaborative, learn to compare branches, resolve conflicts, rebase responsibly, and use pull requests. Keep commits focused, write messages that explain the change, and review staged changes before recording them. Practice recovery commands in a disposable repository before relying on them in an important project.
Most importantly, treat Git as a tool for preserving and communicating the history of your work. A useful repository history helps you and your collaborators understand what changed, why it changed, and how to build on it safely.

A practical GitHub guide to creating repositories, using Git, managing branches and pull requests, automating workflows, protecting code, and releasing projects.
Read
Master the essential Git commands that will transform your workflow and help you collaborate seamlessly with teams while maintaining complete control over your code history.
Read
Explore practical free developer tools for coding, version control, testing, APIs, databases, containers, deployment, security, and collaboration—with the limits to check before you depend on them.
Read