Git and GitHub Cheatsheet
This cheatsheet is a quick reference for developers using Git and GitHub to manage code, collaborate on projects, and automate workflows. It covers essential Git commands, key GitHub features, and an introduction to GitHub Actions, along with best practices and common workflows.
Introduction to Git and GitHub
Git
Git is a distributed version control system created by Linus Torvalds in 2005 for tracking code changes. It allows multiple developers to work on a project simultaneously, maintaining a complete history of changes locally and enabling offline work. Key benefits include:
- Version Control: Track and revert changes easily.
- Collaboration: Merge contributions from multiple developers.
- Branching: Experiment with new features without affecting the main codebase.
GitHub
GitHub is a web-based platform that builds on Git, offering remote repository hosting, collaboration tools, and automation features. It's widely used for open-source and private projects, providing:
- Repositories: Centralized storage for code.
- Issues and Pull Requests: Tools for task tracking and code review.
- GitHub Actions: Automation for CI/CD pipelines.
- GitHub Pages: Hosting for static websites.
Git Commands
Essential Git commands organized by category for quick reference.
Setup & Initialization
| Command | Description |
|---|---|
git init | Initialize a new Git repository in the current directory. |
git clone <url> | Clone a remote repository to your local machine. |
git config --global user.name "Your Name" | Set your username for commit attribution. |
git config --global user.email "your.email@example.com" | Set your email for commit attribution. |
git config --global color.ui auto | Enable colored terminal output. |
Stage & Snapshot
| Command | Description |
|---|---|
git status | Show the current state of the repository (tracked/untracked files, changes). |
git add <file> | Stage a specific file for the next commit. |
git add . | Stage all modified and new files. |
git commit -m "message" | Commit staged changes with a descriptive message. |
git diff | Show changes in the working directory not yet staged. |
git diff --staged | Show changes staged but not committed. |
Branch & Merge
| Command | Description |
|---|---|
git branch | List all branches, with the current branch marked by *. |
git branch <name> | Create a new branch. |
git checkout <name> | Switch to the specified branch. |
git merge <name> | Merge the specified branch into the current branch. |
git branch -d <name> | Delete a branch after merging. |
Share & Update
| Command | Description |
|---|---|
git remote add origin <url> | Add a remote repository with the alias origin. |
git push origin <branch> | Push local branch commits to the remote repository. |
git pull origin <branch> | Fetch and merge changes from the remote branch. |
git fetch origin | Fetch changes from the remote without merging. |
Inspect & Compare
| Command | Description |
|---|---|
git log | Show the commit history for the current branch. |
git log --oneline | Show a condensed commit history. |
git diff <commit1>..<commit2> | Show differences between two commits. |
git show <commit> | Display details of a specific commit. |
Undo Changes
| Command | Description |
|---|---|
git reset --hard HEAD | Reset to the last commit, discarding all changes. |
git reset --soft <commit> | Reset to a commit, keeping changes in the staging area. |
git revert <commit> | Create a new commit that undoes a specific commit. |
git restore <file> | Restore a file to its state in the last commit. |
Other Useful Commands
| Command | Description |
|---|---|
git stash | Save uncommitted changes temporarily. |
git stash pop | Apply and remove the latest stashed changes. |
git tag <tag-name> | Create a tag for a specific commit. |
git rm <file> | Remove a file from the repository and stage the deletion. |
git mv <old> <new> | Rename or move a file and stage the change. |
Git Aliases (Time Savers)
Set up these aliases for faster Git workflows:
# Basic aliases for common commands
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.unstage 'reset HEAD --'
# Advanced aliases for power users
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'
git config --global alias.unstage 'reset HEAD --'
git config --global alias.graph 'log --graph --oneline --decorate --all'
git config --global alias.amend 'commit --amend --no-edit'
git config --global alias.pushf 'push --force-with-lease'
git config --global alias.pom 'push origin main'
git config --global alias.pod 'push origin develop'GitHub Features
GitHub enhances Git with powerful collaboration and project management tools. Below are key features to boost productivity:
Repositories
- Create a Repository: Initialize via the GitHub web interface, adding a README, .gitignore, and LICENSE.
- Clone: Use
git clone https://github.com/username/repo.gitfor HTTPS or SSH for secure cloning. - Collaborators: Invite team members via Settings → Collaborators.
Issues
Track tasks, bugs, or features with titles, descriptions, assignees, labels, and milestones.
Example: Create an issue to track a bug fix, assign it to a developer, and link it to a milestone.
Pull Requests (PRs)
Propose and review code changes.
Steps: Push a branch, create a PR, request reviews, and merge after approval.
Use fixes #issue-number in the PR description or commit message to close related issues.
GitHub Pages
Host static websites from a repository's gh-pages branch or /docs folder.
Example: Create a site at https://username.github.io/repo.
Handy Features
| Feature | Description |
|---|---|
| Ignore Whitespace | Add ?w=1 to diff URLs to exclude whitespace changes (GitHub Secrets). |
| Adjust Tab Size | Add ?ts=4 to diff/file URLs to set tab width to 4 spaces. |
| Task Lists | Use - [ ] in issues/PRs for checkboxes, e.g., - [ ] Fix bug. |
| Close Issues via Commits | Use fixes #123 in commit messages to auto-close issues (Closing Issues). |
| Line Highlighting | Add #L52 or #L53-L60 to file URLs to highlight lines. |
| Emojis | Use :emoji: (e.g., :sparkles:) in comments (Emoji Cheat Sheet). |
GitHub Actions Basics
GitHub Actions is a CI/CD platform for automating workflows like building, testing, and deploying code. Workflows are defined in YAML files stored in .github/workflows/.
Key Components
- Workflow File: YAML file (.yml or .yaml) in
.github/workflows/. - Events: Triggers like
push,pull_request, orschedule(e.g.,on: schedule: - cron: '*/15 * * * *'). - Jobs: Tasks running on virtual machines (e.g.,
runs-on: ubuntu-latest). - Steps: Commands or actions within a job, using
runoruses.
Example Workflow
name: Node.js CI/CD Pipeline
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x, 16.x, 18.x]
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run linter
run: npm run lint
- name: Run tests
run: npm test -- --coverage
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
file: ./coverage/lcov.info
build:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Use Node.js 18.x
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build application
run: npm run build
- name: Upload build artifacts
uses: actions/upload-artifact@v3
with:
name: build-files
path: dist/
deploy:
needs: build
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- name: Download build artifacts
uses: actions/download-artifact@v3
with:
name: build-files
path: dist/
- name: Deploy to production
run: |
echo "Deploying to production server..."
# Add your deployment commands here
- name: Notify deployment status
uses: 8398a7/action-slack@v3
with:
status: completed
webhook_url: your-webhook-url
if: always()Common Actions
| Action | Description |
|---|---|
actions/checkout@v2 | Check out the repository's code. |
actions/setup-node@v2 | Set up a Node.js environment. |
actions/upload-artifact@v2 | Upload build artifacts. |
actions/cache@v2 | Cache dependencies for faster builds. |
Advanced Git Commands and Scripts
Advanced Git commands and automation scripts for power users and development teams.
#!/bin/bash
# Git Repository Setup Script
# Initialize repository
git init
# Set up global configuration (run once per machine)
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
git config --global init.defaultBranch main
git config --global core.editor "code --wait"
git config --global merge.tool vscode
git config --global mergetool.vscode.cmd 'code --wait $MERGED'
git config --global diff.tool vscode
git config --global difftool.vscode.cmd 'code --wait --diff $LOCAL $REMOTE'
# Set up useful aliases
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'
git config --global alias.graph 'log --graph --oneline --decorate --all'
git config --global alias.amend 'commit --amend --no-edit'
git config --global alias.pushf 'push --force-with-lease'
git config --global alias.pom 'push origin main'
git config --global alias.pod 'push origin develop'
git config --global alias.cleanup 'branch --merged | grep -v "\*\|main\|develop" | xargs -n 1 git branch -d'
# Create .gitignore file
cat > .gitignore << EOF
# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Production builds
/dist
/build
*.tgz
*.tar.gz
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage/
*.lcov
# IDE files
.vscode/
.idea/
*.swp
*.swo
*~
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Logs
logs
*.log
# Temporary files
*.tmp
*.temp
EOF
# Create initial README.md
cat > README.md << EOF
# Project Name
Brief description of your project.
## Installation
```bash
npm install
```
## Usage
```bash
npm start
```
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Submit a pull request
## License
MIT License
EOF
# Add files and make initial commit
git add .
git commit -m "Initial commit: Setup project structure"
echo "Git repository initialized with best practices!"
echo "Next steps:"
echo "1. Add remote: git remote add origin <repository-url>"
echo "2. Push to remote: git push -u origin main"#!/bin/bash
# Advanced Git Workflow Scripts
# Function to create and switch to a new feature branch
new_feature() {
if [ -z "$1" ]; then
echo "Usage: new_feature <feature-name>"
return 1
fi
# Ensure we're on main/master
git checkout main 2>/dev/null || git checkout master
git pull origin main 2>/dev/null || git pull origin master
# Create and switch to new branch
git checkout -b "feature/$1"
echo "Created and switched to feature/$1"
}
# Function to finish a feature branch
finish_feature() {
current_branch=$(git branch --show-current)
if [[ $current_branch != feature/* ]]; then
echo "Error: Not on a feature branch"
return 1
fi
# Push feature branch
git push origin "$current_branch"
# Switch back to main
git checkout main
git pull origin main
echo "Feature branch $current_branch pushed to origin"
echo "Create a pull request to merge into main"
}
# Function to clean up merged branches
cleanup_branches() {
echo "Cleaning up merged branches..."
# Delete local branches that have been merged
git branch --merged main | grep -v "\*\|main\|master\|develop" | xargs -n 1 git branch -d
# Clean up remote tracking branches
git remote prune origin
echo "Branch cleanup complete!"
}
# Function to sync with upstream (for forks)
sync_fork() {
if [ -z "$1" ]; then
echo "Usage: sync_fork <upstream-remote-name>"
return 1
fi
# Fetch upstream changes
git fetch "$1"
# Switch to main branch
git checkout main
# Merge upstream changes
git merge "$1/main"
# Push updated main to origin
git push origin main
echo "Fork synced with upstream!"
}
# Function to create a hotfix branch
hotfix() {
if [ -z "$1" ]; then
echo "Usage: hotfix <hotfix-name>"
return 1
fi
# Create hotfix branch from main
git checkout main
git pull origin main
git checkout -b "hotfix/$1"
echo "Created hotfix branch: hotfix/$1"
echo "Make your fixes and run 'finish_hotfix $1'"
}
# Function to finish a hotfix
finish_hotfix() {
if [ -z "$1" ]; then
echo "Usage: finish_hotfix <hotfix-name>"
return 1
fi
hotfix_branch="hotfix/$1"
# Ensure we're on the hotfix branch
git checkout "$hotfix_branch"
# Push hotfix branch
git push origin "$hotfix_branch"
# Merge to main
git checkout main
git merge "$hotfix_branch"
git push origin main
# Merge to develop if it exists
if git show-ref --verify --quiet refs/heads/develop; then
git checkout develop
git merge "$hotfix_branch"
git push origin develop
fi
# Delete hotfix branch
git branch -d "$hotfix_branch"
git push origin --delete "$hotfix_branch"
echo "Hotfix $1 completed and merged!"
}
# Function to squash commits in current branch
squash_commits() {
if [ -z "$1" ]; then
echo "Usage: squash_commits <number-of-commits>"
return 1
fi
git rebase -i "HEAD~$1"
echo "Interactive rebase started. Squash commits as needed."
}
# Function to generate a changelog
generate_changelog() {
echo "# Changelog" > CHANGELOG.md
echo "" >> CHANGELOG.md
# Get all tags
tags=$(git tag -l --sort=-version:refname)
for tag in $tags; do
echo "## $tag" >> CHANGELOG.md
echo "" >> CHANGELOG.md
# Get commits since previous tag
if [ "$tag" = "$(echo "$tags" | tail -n 1)" ]; then
# First tag, get all commits
git log --pretty=format:"- %s (%h)" "$tag" >> CHANGELOG.md
else
# Get commits between tags
prev_tag=$(echo "$tags" | grep -A 1 "$tag" | tail -n 1)
git log --pretty=format:"- %s (%h)" "$prev_tag..$tag" >> CHANGELOG.md
fi
echo "" >> CHANGELOG.md
echo "" >> CHANGELOG.md
done
echo "Changelog generated in CHANGELOG.md"
}
# Export functions for use
export -f new_feature finish_feature cleanup_branches sync_fork
export -f hotfix finish_hotfix squash_commits generate_changelog
echo "Advanced Git workflow functions loaded!"
echo "Available commands:"
echo " new_feature <name> - Create new feature branch"
echo " finish_feature - Finish current feature branch"
echo " cleanup_branches - Clean up merged branches"
echo " sync_fork <upstream> - Sync fork with upstream"
echo " hotfix <name> - Create hotfix branch"
echo " finish_hotfix <name> - Finish hotfix branch"
echo " squash_commits <n> - Squash last n commits"
echo " generate_changelog - Generate changelog from git tags"#!/bin/bash
# GitHub CLI Automation Scripts
# Requires: gh cli tool (https://cli.github.com/)
# Function to create a new repository
create_repo() {
if [ -z "$1" ]; then
echo "Usage: create_repo <repo-name>"
return 1
fi
repo_name="$1"
# Create repository
gh repo create "$repo_name" --public
# Clone the repository
gh repo clone "$repo_name"
cd "$repo_name" || return 1
echo "Repository $repo_name created and cloned!"
}
# Function to create a pull request
create_pr() {
if [ -z "$1" ]; then
echo "Usage: create_pr <title>"
return 1
fi
title="$1"
# Create PR with default template
gh pr create --title "$title" --body "## Changes
- List your changes here
## Testing
- [ ] Tests pass locally
- [ ] Code follows style guidelines
- [ ] Self-review completed"
echo "Pull request created: $title"
}
# Function to review and merge PR
review_pr() {
if [ -z "$1" ]; then
echo "Usage: review_pr <pr-number>"
return 1
fi
pr_number="$1"
# Approve and merge PR
gh pr review "$pr_number" --approve
gh pr merge "$pr_number" --squash
echo "PR #$pr_number approved and merged"
}
# Function to create an issue
create_issue() {
if [ -z "$1" ]; then
echo "Usage: create_issue <title>"
return 1
fi
title="$1"
# Create issue with template
gh issue create --title "$title" --body "## Description
Please describe the issue
## Steps to Reproduce
1. Step one
2. Step two
3. Step three
## Expected Behavior
What should happen
## Actual Behavior
What actually happens"
echo "Issue created: $title"
}
# Function to create a release
create_release() {
if [ -z "$1" ]; then
echo "Usage: create_release <version>"
return 1
fi
version="$1"
# Create release with auto-generated notes
gh release create "$version" --title "Release $version" --generate-notes
echo "Release $version created!"
}
# Common GitHub CLI commands
echo "GitHub CLI Quick Commands:"
echo " gh repo list - List your repositories"
echo " gh repo view - View current repository"
echo " gh pr list - List pull requests"
echo " gh pr status - Show PR status"
echo " gh issue list - List issues"
echo " gh workflow list - List GitHub Actions workflows"
echo " gh workflow run <workflow> - Run a workflow"
echo " gh auth status - Check authentication status"
echo " gh auth login - Login to GitHub"Best Practices
- Commit Frequently: Make small, focused commits with clear messages (e.g.,
fix: resolve login bug). - Use Descriptive Messages: Follow conventions like
feat:,fix:,docs:, orrefactor:. - Branch for Features: Develop features in separate branches to keep master stable.
- Pull Regularly: Stay updated with
git pull origin masterto avoid conflicts. - Write Clear PRs: Include context, changes, and testing steps in pull request descriptions.
- Track Tasks with Issues: Use issues for bugs, features, and discussions, linking them to PRs.
- Secure Workflows: Use specific action versions (e.g.,
@v2) and protect secrets in GitHub Actions.
Common Git Workflows
1. Feature Branch Workflow
| Step | Command |
|---|---|
| Create branch | git checkout -b feature/new-feature |
| Make changes | Edit files, then git add . and git commit -m "feat: add new feature" |
| Push branch | git push origin feature/new-feature |
| Create PR | Use GitHub's web interface to open a pull request. |
2. Merging a Feature
| Step | Command |
|---|---|
| Switch to master | git checkout master |
| Update master | git pull origin master |
| Merge feature | git merge feature/new-feature |
| Push changes | git push origin master |
3. Resolving Merge Conflicts
| Step | Command |
|---|---|
| Identify conflicts | Git pauses merge and lists conflicting files. |
| Edit files | Manually resolve conflicts in affected files. |
| Stage resolved files | git add <file> |
| Complete merge | git commit -m "Resolve merge conflicts" |
4. Rebasing Instead of Merging
| Step | Command |
|---|---|
| Switch to feature | git checkout feature/new-feature |
| Rebase onto master | git rebase master |
| Resolve conflicts | Edit files, then git add <file> and git rebase --continue |
| Force push | git push origin feature/new-feature --force |
Conclusion
This cheatsheet provides essential Git and GitHub commands for developers. Keep this reference handy to boost productivity and maintain clean, organized projects.