Search

Git Cheat Sheet

Git Cheat Sheet: Helpful Git Commands with Examples

1. Git Configuration

  • Set your user name and email:

    git config --global user.name "Your Name"
    git config --global user.email "your.email@example.com"
  • View your current configuration:

    git config --list

2. Initialize a Repository

  • Create a new Git repository:

    git init
  • Clone an existing repository:

    git clone <repository-url>

3. Basic Workflow

  • Check the status of your repository:

    git status
  • Stage changes for commit:

    git add <file-name>   # Add specific file
    git add .             # Add all changes
  • Commit changes with a message:

    git commit -m "Descriptive commit message"
  • View commit history:

    git log

4. Branching and Merging

  • Create a new branch:

    git branch <branch-name>
  • Switch to another branch:

    git checkout <branch-name>
  • Create and switch to a new branch:

    git checkout -b <branch-name>
  • Merge a branch into the current branch:

    git merge <branch-name>

5. Syncing with Remote

  • Add a remote repository:

    git remote add origin <remote-url>
  • Push changes to a remote repository:

    git push origin <branch-name>
  • Fetch changes from the remote:

    git fetch origin
  • Pull changes from the remote (fetch + merge):

    git pull origin <branch-name>

6. Stashing Changes

  • Stash uncommitted changes:

    git stash
  • View stashed changes:

    git stash list
  • Apply stashed changes:

    git stash apply

7. Undoing Changes

  • Undo changes to a file (reset to last commit):

    git checkout -- <file-name>
  • Remove files from the staging area (without deleting them):

    git reset <file-name>
  • Undo the last commit (keep changes):

    git reset --soft HEAD~1

8. Deleting and Renaming

  • Delete a file:

    git rm <file-name>
  • Rename a file:

    git mv <old-name> <new-name>

9. Tagging a Release

  • Create a tag:

    git tag <tag-name>
  • Push a tag to the remote:

    git push origin <tag-name>

10. Git Shortcuts

  • Amend the last commit (e.g., to change the commit message):

    git commit --amend -m "Updated commit message"
  • View changes between commits:

    git diff <commit-id1> <commit-id2>

11. Resetting Commits

  • Reset to a specific commit (discard all changes after it):
    git reset --hard <commit-id>

12. Viewing and Managing Logs

  • Compact log view:
    git log --oneline --graph

13. Git Aliases

  • Set an alias for a Git command:

    git config --global alias.st status

    Now you can use git st instead of git status.