This comprehensive guide covers essential and advanced commands for managing local and remote repositories, branches, pull requests, and interactions with GitHub using both Git and GitHub CLI tools. Master these commands to become a GitHub power user.
- 1. Repository Setup & Cloning
- 2. Branch Management
- 3. Fetching, Pulling, and Syncing
- 4. Committing Changes
- 5. Pushing Changes
- 6. Working with Pull Requests Using GitHub CLI
- 7. Issues and Labels
- 8. Working with GitHub Actions and Checks
- 9. Custom Aliases (GitHub CLI)
- 10. Advanced Git Techniques
- 11. GitHub CLI Extensions
- 12. Troubleshooting
- Summary
- Additional Resources
Clone repository with SSH:
git clone git@github.com:owner/repo.gitClone with HTTPS:
git clone https://github.com/owner/repo.gitClone specific branch:
git clone -b branch-name https://github.com/owner/repo.gitShallow clone (faster, less history):
git clone --depth 1 https://github.com/owner/repo.gitFork and clone in one command:
gh repo fork owner/repo --clone=trueFork without cloning:
gh repo fork owner/repoClone existing fork:
git clone https://github.com/YOUR_USERNAME/repo.gitAdd upstream remote:
git remote add upstream https://github.com/ORIGINAL_OWNER/repo.gitRename origin to your fork:
git remote set-url origin https://github.com/YOUR_USERNAME/repo.gitVerify remote configuration:
git remote -vList local branches:
git branchList remote branches:
git branch -rList all branches:
git branch -aShow current branch:
git branch --show-currentCreate and switch to new branch:
git checkout -b feature/new-feature
# or
git switch -c feature/new-featureSwitch to existing branch:
git checkout existing-branch
# or
git switch existing-branchCreate branch from specific commit:
git checkout -b new-branch abc123Rename current branch:
git branch -m new-branch-nameDelete local branch:
git branch -d branch-nameForce delete local branch:
git branch -D branch-nameDelete remote branch:
git push origin --delete branch-nameTrack remote branch:
git checkout --track origin/remote-branchFetch all branches from origin:
git fetch originFetch from upstream:
git fetch upstreamFetch specific branch:
git fetch origin branch-namePull with merge (default):
git pull origin mainPull with rebase (linear history):
git pull --rebase origin mainPull specific branch:
git pull origin feature-branchSync fork with upstream:
git checkout main
git fetch upstream
git rebase upstream/main
git push origin mainAlternative merge approach:
git checkout main
git fetch upstream
git merge upstream/main
git push origin mainStage specific file:
git add filename.txtStage all changes:
git add .Stage interactively:
git add -pUnstage file:
git reset filename.txtCommit with message:
git commit -m "feat: add new feature"Commit all staged changes:
git commit -a -m "fix: resolve bug"Amend last commit:
git commit --amendAmend without changing message:
git commit --amend --no-editEmpty commit:
git commit --allow-empty -m "trigger: ci build"Commit with specific author:
git commit --author="Name <email@example.com>" -m "message"Push current branch:
git push origin current-branchPush with upstream tracking:
git push -u origin feature-branchPush all branches:
git push --all originSafe force push:
git push --force-with-lease origin branchDangerous force push:
git push --force origin branchPush tags:
git push --tagsPush to different remote:
git push upstream mainDry run push:
git push --dry-run origin branchCheck PR status:
gh pr statusList PRs:
gh pr listView PR details:
gh pr view 123View PR in browser:
gh pr view --web 123Create PR interactively:
gh pr createCreate PR with options:
gh pr create --title "feat: add authentication" \
--body "Implements user login..." \
--base main \
--head feature/authCreate draft PR:
gh pr create --draftCheckout PR locally:
gh pr checkout 123Update PR branch:
gh pr update-branch 123Merge PR:
gh pr merge 123Merge with options:
gh pr merge 123 --squash --delete-branchList PR reviews:
gh pr review --list 123Approve PR:
gh pr review 123 --approveRequest changes:
gh pr review 123 --request-changes --body "Please fix..."List issues:
gh issue listList issues with filters:
gh issue list --label "bug" --state openView issue:
gh issue view 123Create issue:
gh issue create --title "Bug: app crashes" --body "Steps to reproduce..."Close issue:
gh issue close 123Reopen issue:
gh issue reopen 123Edit issue:
gh issue edit 123 --title "New title"List labels:
gh label listCreate label:
gh label create "priority: high" --color FF0000Apply label to issue:
gh issue edit 123 --add-label "bug"Remove label:
gh issue edit 123 --remove-label "bug"List workflows:
gh workflow listView workflow:
gh workflow view "CI"Run workflow:
gh workflow run "CI"List runs:
gh run listView run details:
gh run view 12345Rerun failed run:
gh run rerun 12345Download run artifacts:
gh run download 12345View PR checks:
gh pr checks 123Wait for checks:
gh pr checks 123 --watchAdd simple alias:
gh alias set prc 'pr create --web'Add complex alias:
gh alias set review 'pr checkout $1 && pr diff'List aliases:
gh alias listDelete alias:
gh alias delete prc# Quick PR creation
gh alias set prnew 'pr create --fill'
# Status overview
gh alias set status 'repo view && echo "---" && pr status && echo "---" && issue list --limit 5'
# Branch cleanup
gh alias set clean-branches 'pr list --state merged --json number,headRefName --jq ".[].headRefName" | xargs -I {} git branch -D {}'Rebase last 3 commits:
git rebase -i HEAD~3Rebase onto different branch:
git rebase --onto main feature-branchCherry pick commit:
git cherry-pick abc123Cherry pick range:
git cherry-pick abc123..def456Stash changes:
git stash push -m "work in progress"Apply stash:
git stash popList stashes:
git stash listView reflog:
git reflogRecover lost commit:
git checkout -b recovery abc123Install extension:
gh extension install owner/gh-extension-nameList installed extensions:
gh extension listUpgrade extensions:
gh extension upgrade --allgh pr-cleanup- Clean up merged branchesgh notify- Notificationsgh dash- Dashboardgh copilot- GitHub Copilot integration
Resolve merge conflicts:
git status
# Edit conflicted files
git add resolved-file
git commitUndo last commit:
git reset --soft HEAD~1 # keep changes
git reset --hard HEAD~1 # discard changesRecover deleted branch:
git reflog
git checkout -b recovered-branch abc123Authentication problems:
gh auth login
gh auth refreshPermission denied:
gh auth status
# Check token scopesRate limiting:
gh api -H "Accept: application/vnd.github.v3+json" /rate_limitPre-commit hooks:
#!/bin/sh
# .git/hooks/pre-commit
# Run linting
npm run lint
# Run tests
npm test
# Check for secrets
git secrets --pre_commit_hookPre-push hooks:
#!/bin/sh
# .git/hooks/pre-push
# Run full test suite
npm run test:full
# Check code coverage
npm run coverage -- --check-coverageSetup Husky:
npm install husky --save-dev
npx husky install
# Add hooks
npx husky add .husky/pre-commit "npm run lint"
npx husky add .husky/pre-push "npm test"Advanced Husky configuration:
// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
"pre-push": "npm run test"
}
},
"lint-staged": {
"*.{js,ts}": ["eslint --fix", "prettier --write"],
"*.{md,mdx}": ["prettier --write"]
}
}GitHub webhooks integration:
# .github/workflows/webhook-handler.yml
name: Handle Webhooks
on:
repository_dispatch:
types: [custom-event]
jobs:
handle:
runs-on: ubuntu-latest
steps:
- name: Process webhook
run: |
echo "Event: ${{ github.event.action }}"
echo "Sender: ${{ github.event.sender.login }}"Rebase with editing:
git rebase -i HEAD~5
# Commands:
# pick - use commit
# reword - edit message
# edit - amend commit
# squash - merge with previous
# fixup - merge without message
# drop - remove commitRebase onto different branch:
git rebase --onto main feature-branch bugfix-branchDuring rebase conflicts:
# Resolve conflicts in files
git add resolved-file
# Continue rebase
git rebase --continue
# Skip conflicted commit
git rebase --skip
# Abort rebase
git rebase --abortLinear history maintenance:
# Before merging feature branch
git checkout feature-branch
git rebase main
git checkout main
git merge feature-branch # Fast-forward mergeSquashing for clean history:
git rebase -i --autosquash main
# Automatically groups fixup! and squash! commitsCreate worktree:
git worktree add ../feature-branch feature-branch
cd ../feature-branchList worktrees:
git worktree listRemove worktree:
git worktree remove feature-branchWorktree for hotfixes:
# Create worktree for hotfix
git worktree add -b hotfix/urgent-fix ../hotfix urgent-fix
# Work on hotfix
cd ../hotfix
# Make changes
git commit -m "fix: urgent security patch"
# Push and create PR
git push -u origin hotfix/urgent-fix
gh pr create --fill
# Remove worktree after merge
git worktree remove ../hotfixWorktree for experiments:
# Create experimental worktree
git worktree add ../experiment experiment
# Experiment freely
cd ../experiment
git reset --hard HEAD~10 # Go back in history
# Test different approaches
# Discard experiment
cd ..
rm -rf experiment
git worktree pruneEssential config:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
git config --global core.editor "code --wait"
git config --global init.defaultBranch main
git config --global pull.rebase trueAdvanced config:
# Enable rerere (reuse recorded resolution)
git config --global rerere.enabled true
# Better diff output
git config --global diff.algorithm histogram
# Colored output
git config --global color.ui auto
# Push only current branch
git config --global push.default simpleWorkflow aliases:
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'Advanced aliases:
# Show contributors
git config --global alias.contributors 'shortlog -sn --no-merges'
# Find commits by message
git config --global alias.find 'log --all --grep'
# Show file history
git config --global alias.filelog 'log -p --follow --'
# Clean merged branches
git config --global alias.clean-branches '!git branch --merged | grep -v "\*" | xargs -n 1 git branch -d'Per-repository config:
# .git/config
[user]
name = Work Name
email = work@example.com
[core]
sshCommand = ssh -i ~/.ssh/work_keyInclude files:
# ~/.gitconfig
[include]
path = ~/.gitconfig-work
[includeIf "gitdir:~/personal/"]
path = ~/.gitconfig-personalCustom GitHub Apps:
// GitHub App webhook handler
app.on('pull_request.opened', async (context) => {
const pr = context.payload.pull_request;
// Auto-label PR based on branch
if (pr.head.ref.startsWith('feature/')) {
await context.github.issues.addLabels({
owner: pr.base.repo.owner.login,
repo: pr.base.repo.name,
issue_number: pr.number,
labels: ['enhancement']
});
}
});Automated repository management:
# Create issue with GitHub CLI
gh issue create \
--title "Automated: Dependency Update" \
--body "Dependencies have been updated automatically." \
--label "dependencies,automated"
# Bulk operations
gh issue list --label "stale" --json number --jq '.[].number' | \
xargs -I {} gh issue edit {} --add-label "closing-soon"GitHub Actions with Git operations:
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Full history for tags
- name: Create release branch
run: |
git checkout -b release/v${{ github.event.inputs.version }}
git push -u origin release/v${{ github.event.inputs.version }}
- name: Create tag
run: |
git tag -a v${{ github.event.inputs.version }} -m "Release v${{ github.event.inputs.version }}"
git push origin v${{ github.event.inputs.version }}Shallow clones for CI:
git clone --depth 1 https://github.com/user/repo.gitPartial clones:
git clone --filter=blob:none https://github.com/user/repo.git
# Download blobs on demandGC optimization:
git config --global gc.auto 0 # Disable auto GC
git gc --aggressive --prune=now # Manual optimizationGit LFS for large files:
git lfs install
git lfs track "*.psd" "*.mov"
git add .gitattributesSparse checkout:
git sparse-checkout init --cone
git sparse-checkout set docs/SSH multiplexing:
# ~/.ssh/config
Host github.com
ControlMaster auto
ControlPath ~/.ssh/master-%r@%h:%p
ControlPersist 10mParallel fetching:
git config --global fetch.parallel 0 # Use all CPUsSign commits:
git config --global commit.gpgsign true
git config --global user.signingkey YOUR_KEY_IDVerify signatures:
git log --show-signatureBranch protection:
- Require PR reviews
- Require status checks
- Include administrators
- Restrict pushes
Token management:
# Use fine-grained tokens
gh auth login --scopes "repo,workflow"
# Rotate tokens regularly
gh auth refreshGitHub secrets:
# Use in workflows
- name: Deploy
run: |
echo "API_KEY=${{ secrets.API_KEY }}" >> .envEnvironment-specific secrets:
jobs:
deploy:
environment: production
steps:
- run: echo "Using ${{ secrets.PROD_API_KEY }}"Git improvements:
- Sparse index for large repos
- Multi-pack index for performance
- Commit graphs for faster operations
- Partial clones evolution
GitHub innovations:
- GitHub Copilot integration
- Codespaces for cloud development
- Discussions for community engagement
- Projects for project management
GitHub Teams and Organizations:
- Nested teams for complex hierarchies
- Team sync with identity providers
- Organization-wide insights
- Enterprise features
Integration ecosystem:
- Marketplace apps expansion
- API evolution with GraphQL
- Webhook enhancements
- Real-time collaboration
Mastering Git and GitHub CLI commands transforms you from a basic user to a power contributor. Combine Git's version control with GitHub's collaboration features to streamline your development workflow. Regular practice and exploration of advanced features will make these commands second nature.