Git

2025.12.15

Basic Operations

CommandDescription
git initInitialize a new repository
git clone <url>Clone a repository
git statusCheck working directory status
git add <file>Stage a file
git add .Stage all changes
git commit -m "message"Create a commit
git pushPush to remote
git pullPull from remote

Branch Operations

CommandDescription
git branchList branches
git branch <name>Create a new branch
git checkout <branch>Switch to a branch
git checkout -b <name>Create and switch to a new branch
git merge <branch>Merge a branch
git branch -d <name>Delete a branch

History

CommandDescription
git logShow commit history
git log --onelineShow history in one line
git log --graphShow history as a graph
git diffShow differences
git show <commit>Show commit details

Undo Operations

CommandDescription
git reset HEAD <file>Unstage a file
git checkout -- <file>Discard working directory changes
git revert <commit>Revert a commit (creates new commit)
git reset --hard <commit>Reset to a commit (dangerous)

Remote Operations

CommandDescription
git remote -vList remotes
git remote add <name> <url>Add a remote
git fetchFetch remote information
git push -u origin <branch>Push and set upstream branch

Useful Aliases

# Add to ~/.gitconfig
[alias]
    st = status
    co = checkout
    br = branch
    ci = commit
    lg = log --oneline --graph --decorate
    unstage = reset HEAD --
    last = log -1 HEAD
    amend = commit --amend --no-edit

Troubleshooting

SituationSolution
Wrong commit messagegit commit --amend -m "new message"
Committed by mistakegit reset --soft HEAD~1 to undo
Merge conflictEdit files → git addgit commit
Push rejectedgit pull --rebase then push again
Restore specific filegit checkout <commit> -- <file>

Branch Workflow Best Practices

# Feature development flow
git checkout -b feature/user-auth     # Create feature branch
# ... development work ...
git add . && git commit -m "feat: implement user auth"
git push -u origin feature/user-auth  # Push
# Create PR, review, then merge
git checkout main && git pull         # Update main
git branch -d feature/user-auth       # Delete local branch
← Back to list