Learn Git Commands
A quick reference guide for the most common Git commands and use cases.
⚙️ Setup & Configuration
git config --global user.name 'Your Name'
Set the name that will be attached to your commits.
git config --global user.email 'youremail@example.com'
Set the email that will be attached to your commits.
git config --global init.defaultBranch main
Set the default branch name to 'main' for new repositories.
🚀 Starting a Project
git init
Initialize a new, empty Git repository in the current directory.
git clone https://github.com/user/repo.git
Create a local copy of a remote repository.
🛠️ Daily Workflow
git status
Show the working tree status (untracked, modified, and staged files).
git add <file>
Add file contents to the index (staging area). Use `git add .` to add all changes.
git commit -m 'Your commit message'
Record changes to the repository with a descriptive message.
git push
Update the remote repository with your committed changes.
git pull
Fetch changes from the remote repository and merge them into your current branch.
🌿 Branching & Merging
git branch
List all local branches. Add `-r` for remote or `-a` for all branches.
git branch <branch-name>
Create a new branch.
git checkout <branch-name>
Switch to an existing branch. Use `-b` to create and switch to a new branch in one step (`git checkout -b <new-branch>`).
git merge <branch-name>
Join the specified branch's history into the current branch.
git rebase <branch-name>
Re-apply commits from your current branch onto the tip of another branch, creating a cleaner, linear history.
⏪ Undoing Changes
git commit --amend
Modify the most recent commit. Useful for fixing typos in the commit message or adding forgotten changes.
git reset HEAD <file>
Unstage a file, but preserve its content in the working directory.
git reset --soft HEAD~1
Undo the last commit but keep the changes staged.
git reset --hard HEAD~1
DANGEROUS: Discard the last commit and all changes in the working directory. Use with caution.
git revert <commit-hash>
Create a new commit that undoes the changes of a previous commit, safely preserving history.
🔎 Inspecting History
git log
Show the commit history. Use `--oneline` for a compact view.
git log --graph --oneline --decorate
Display the commit history as a visual graph.
git diff
Show changes between commits, commit and working tree, etc. `git diff --staged` shows changes in the staging area.
git show <commit-hash>
Show metadata and content changes of the specified commit.
🤝 Working with Remotes
git remote -v
List all remote repositories.
git remote add origin <url>
Add a new remote repository.
git fetch origin
Download objects and refs from another repository without merging.
git push -u origin main
Push a local branch to a remote repository and set it as the upstream branch.