# Git Cheat Sheet ## Basics - **Initialize a Git Repository**: `git init` - **Clone a Repository**: `git clone <repository-url>` - **Check Repository Status**: `git status` - **Add Changes to Staging Area**: `git add <file>` or `git add .` (for all changes) - **Commit Changes**: `git commit -m "Commit message"` - **View Commit History**: `git log` - **Undo Last Commit (Keep Changes)**: `git reset HEAD~1` - **Discard Changes in Working Directory**: `git checkout -- <file>` - **Create a Branch**: `git checkout -b <branch-name>` - **Switch Branches**: `git checkout <branch-name>` - **Merge Branch**: `git merge <branch-name>` ## Branching and Merging - **List Branches**: `git branch` - **Delete a Branch (Locally)**: `git branch -d <branch-name>` - **Delete a Branch (Force)**: `git branch -D <branch-name>` - **Merge Branch into Current Branch**: `git merge <branch-name>` - **Merge Branch with Fast-Forward**: `git merge --ff-only <branch-name>` - **Rebase Current Branch onto Another Branch**: `git rebase <branch-name>` - **Abort a Merge/Rebase**: `git merge --abort` or `git rebase --abort` - **View Merged/Rebased Commits**: `git reflog` ## Remote Repositories - **Add a Remote Repository**: `git remote add <remote-name> <repository-url>` - **List Remote Repositories**: `git remote -v` - **Fetch Changes from a Remote Repository**: `git fetch <remote-name>` - **Pull Changes from a Remote Repository**: `git pull <remote-name> <branch-name>` - **Push Changes to a Remote Repository**: `git push <remote-name> <branch-name>` - **Remove a Remote**: `git remote remove <remote-name>` ## Collaborative Work - **Create a Pull Request**: Open one on your Git hosting platform. - **Review and Merge Pull Request**: Done via the hosting platform. - **Sync Fork with Upstream Repository**: `git fetch upstream`, `git merge upstream/main` - **Resolve Merge Conflicts**: Edit conflicted files, `git add`, and `git commit` ## Undo and History - **Undo Last Commit (Keep Changes)**: `git reset HEAD~1` - **Undo Last Commit (Discard Changes)**: `git reset --hard HEAD~1` - **Revert a Commit**: `git revert <commit-hash>` - **View Commit History**: `git log` - **Show Changes in a Specific Commit**: `git show <commit-hash>` - **View Differences Between Branches**: `git diff <branch1> <branch2>` ## Stashing - **Stash Changes**: `git stash` - **List Stashes**: `git stash list` - **Apply Stash**: `git stash apply` or `git stash pop` - **Delete Stash**: `git stash drop <stash-id>` ## Git Config - **Set User Name**: `git config --global user.name "Your Name"` - **Set User Email**: `git config --global user.email "your@email.com"` - **View Git Config**: `git config --list` ## Tags - **Create a Tag**: `git tag -a <tag-name> -m "Tag message"` - **List Tags**: `git tag` - **Push Tags to Remote**: `git push --tags`