🐙 Git and GitHub CLI
Basic and advanced Git commands for version control, branching, remote repositories, stash, tags, and the GitHub CLI.
🔹 Basic Commands
| Command | Example | Description | 
|---|---|---|
| git add | Add a file to the staging area | |
| git add file.txt | Stage a specific file for the next commit | |
| git add . | Stage all changes in the current folder and below | |
| git add -p | Interactively choose which parts of files to stage (useful for partial commits) | |
| git clone | Clone a repository into a new folder | |
| git clone -b branch_name URL | Clone only the specified branch (instead of the default) | |
| git clone --depth 1 URL | Clone only the latest commit, making a shallow copy to save time and space | |
| git commit | Record changes to the repository | |
| git commit -m "Initial commit" | Commit with a message without opening the editor | |
| git commit -a -m "Fix bugs" | Stage and commit all modified tracked files with a message | |
| git commit --amend | Amend the last commit (change message or include more changes) | |
| git commit --fixup abc1234 | Create a fix-up commit to be squashed automatically during interactive rebase | |
| git config | View and set repository or global options | |
| git config --global user.name "Name" | Set global Git username | |
| git config --global user.email "email@example.com" | Set global Git email | |
| git config --list | List all Git settings (name, email, editor, etc.) | |
| git diff | Show differences between commits, or between a commit and the working tree | |
| git diff HEAD | Show what you have changed since the last commit (unstaged changes) | |
| git diff --staged | Show what will be included in the next commit | |
| git diff --word-diff HEAD~1 | Show changes with word-level differences | |
| git grep | Search inside repository files | |
| git grep "functionName" | Find all mentions of  | |
| git grep -n "TODO" | Find lines containing  | |
| git grep -i "login" | Search for the word  | |
| git init | Create an empty Git repository or reinitialise an existing one | |
| git init my-project | Initialise a new repo in folder my-project | |
| git init --bare | Initialise a bare repository | |
| git log | Show commit logs | |
| git log --oneline | Display commit history in a compact one-line format | |
| git log --graph --all | Show all branches in a visual graph of commits | |
| git log -p --stat | Show patch and file change statistics for commits | |
| git reset | Unstage files while keeping changes in the working directory | |
| git reset HEAD file.txt | Remove a file from staging (keeps your edits) | |
| git reset --hard HEAD~1 | Revert one commit and delete all changes (irreversible!) | |
| git reset --soft HEAD~1 | Undo the last commit but keep the changes staged | |
| git reset --mixed HEAD~1 | Undo a commit but keep changes unstaged in the working directory | |
| git show | Display information about various Git objects | |
| git show <commit_hash> | Show changes and the message of a specific commit | |
| git show HEAD~1 | Show the previous commit before the current one | |
| git show --stat | Show a summary of file changes for the latest commit | |
| git status | Display the working tree status | |
| git status -s | Show status in short format | |
| git status -b | Show current branch and file statuses | 
🌿 Branching and Merging
| Command | Example | Description | 
|---|---|---|
| git branch | Create, list, or delete branches | |
| git branch new-feature | Create a new branch called  | |
| git branch -d old-feature | Delete a local branch named  | |
| git checkout | Switch branches or restore files from another commit | |
| git checkout main | Switch to the  | |
| git checkout -b new-branch | Create and switch to a new branch named  | |
| git switch | Switch branches (simplified alternative to checkout) | |
| git switch main | Switch to the  | |
| git switch -c feature-x | Create and switch to a new branch named  | |
| git switch new-feature | Switch to an existing branch named  | |
| git merge | Merge changes from another branch into the current one | |
| git merge new-feature | Merge the  | |
| git merge --no-ff new-feature | Always create a merge commit (even if fast-forward is possible) | |
| git merge --abort | Cancel the merge and revert changes if conflicts occur | |
| git rebase | Reapply commits on top of a new base commit | |
| git rebase main | Rebase your branch on top of the  | |
| git rebase -i HEAD~3 | Interactively edit the last 3 commits | |
| git rebase --abort | Abort and undo an in-progress rebase | |
| git rebase -i --autosquash HEAD~5 | Automatically squash fix-up or squash commits during interactive rebase | |
| git cherry-pick | Apply specific commits from another branch | |
| git cherry-pick <hash> | Apply a specific commit (by hash) to the current branch | |
| git cherry-pick --continue | Continue cherry-pick after resolving conflicts | |
| git cherry-pick A^..B | Apply a range of commits from  | 
📡 Remote Repositories
| Command | Example | Description | 
|---|---|---|
| git remote | Manage links to remote repositories (e.g. GitHub) | |
| git remote -v | List remote names and their URLs | |
| git remote add origin URL | Add a remote repository named  | |
| git pull | Download and automatically merge changes from a remote branch | |
| git pull origin main | Fetch and merge changes from the remote  | |
| git pull --rebase origin main | Fetch and rebase your current branch on top of the remote branch instead of merging | |
| git push | Upload your local changes to a remote repository | |
| git push origin main | Push your local  | |
| git fetch | Download changes from remote without merging | |
| git fetch origin | Fetch all updates from  | |
| git fetch origin main | Fetch only the  | |
| git fetch --all | Fetch updates from all remotes | |
| git fetch --prune | Clean up deleted branches — remove local refs to branches deleted remotely | |
| git fetch --dry-run | Show what would be fetched, without actually downloading anything | |
| git fetch origin +main | Forcefully update your local tracking branch ( | 
📦 Stash and Clean-up
| Command | Example | Description | 
|---|---|---|
| git stash | Temporarily save uncommitted changes (work in progress) | |
| git stash | Save modified and staged files, then revert the working directory to the last commit | |
| git stash apply | Reapply the latest stashed changes (stash remains saved) | |
| git stash pop | Reapply and remove the latest stash | |
| git stash list | List all stashed changes | |
| git stash branch feature-fix | Create a new branch and apply the latest stash to it | |
| git clean | Permanently delete untracked files (not in Git) | |
| git clean -f | Delete untracked files in the current folder | |
| git clean -fd | Delete untracked files and folders | |
| git clean -n | Preview what will be deleted (safe dry run) | 
🏷️ Tags
| Command | Example | Description | 
|---|---|---|
| git tag | Create, list, or delete tags to mark specific points in history (e.g. releases) | |
| git tag -a v1.0 -m "Version 1.0" | Create an annotated tag named  | |
| git tag -d v1.0 | Delete the local tag named  | |
| git push | Upload commits, branches, and tags from local to remote repository | |
| git push origin --tags | Push all local tags to remote (useful after tagging multiple versions) | |
| git push origin v1.0 | Push a specific tag (e.g.  | |
| git push origin :refs/tags/v1.0 | Delete the remote tag  | 
🛠️ Conflict Resolution
| Command | Example | Description | 
|---|---|---|
| git mergetool | Open a visual tool to assist with resolving merge conflicts | |
| git mergetool --tool=meld | Use a specific merge tool (such as Meld) to fix conflicts | |
| git rerere | Allow Git to remember how you resolved merge conflicts previously | |
| git config --global rerere.enabled true | Enable automatic reuse of past conflict resolutions | |
| git rerere status | Show which files have saved conflict resolutions | |
| git rerere diff | Display what changes Git saved for future reuse | 
⚙️ Advanced Commands
| Command | Example | Description | 
|---|---|---|
| git bisect | Use binary search to identify the commit that introduced a bug | |
| git bisect start | Start a binary search between a known good and a bad commit to locate a bug | |
| git bisect bad | Mark the current commit as ‘bad’ (contains the bug) | |
| git bisect good <commit> | Mark a known ‘good’ commit where the bug did not exist | |
| git blame | Show who last modified each line of a file, with revision and author | |
| git blame file.txt | Show the author and commit information for every line in the file | |
| git blame -L 10,20 file.txt | Display blame information only for lines 10 to 20 | |
| git blame --show-email file.txt | Show authors’ email addresses alongside line changes | |
| git reflog | View and manage the reference log (reflog) of branch movements and HEAD | |
| git reflog show main@{1.week.ago} | See where the  | |
| git reflog expire --expire=30.days --dry-run | Preview which reflog entries older than 30 days can be cleaned (no changes made) | |
| git reflog delete HEAD@{2} | Delete a specific reflog entry (use carefully, as it may affect recovery) | |
| git submodule | Add, initialise, update, or inspect submodules (repositories inside repositories) | |
| git submodule add URL path | Add an external repository as a submodule in the specified path | |
| git submodule update --init | Initialise and download all submodules listed in the repository | |
| git submodule foreach git pull | Run  | |
| git submodule sync --recursive | Synchronise submodule URLs after changes in the  | |
| git submodule update --remote --merge | Update submodules to the latest commit from their remote branches | |
| git archive | Create an archive (ZIP, TAR, etc.) of files from a specific commit or branch | |
| git archive --format=zip HEAD > archive.zip | Create a ZIP archive of the current project files at HEAD | |
| git archive -o release.tar.gz HEAD | Create a compressed  | |
| git archive --format=tar --prefix=project/ HEAD \| gzip > project.tar.gz | Create a compressed  | |
| git gc | Clean up unnecessary files and optimise the repository for performance | |
| git gc --aggressive | Perform a thorough clean-up and optimisation (can be slow but effective) | |
| git gc --prune=now | Remove all unreachable objects immediately (dangerous if unsure) | |
| git shortlog | Quick summary of authors and their commits | |
| git shortlog -e | List authors with their email addresses (e.g. to analyse who contributed and how much) | |
| git shortlog -s -n | Show how many commits each author made, sorted by number of commits | |
| git shortlog -sne | Same as above, but also include names and email addresses — useful for detailed activity tracking | |
| git revert | Create a new commit that undoes changes from a previous commit without rewriting history | |
| git revert HEAD | Undo the last commit by creating a new commit that reverses its changes | |
| git revert <commit_hash> | Undo a specific commit by hash, safely adding a new commit that reverses it | 
🐙 GitHub CLI
ghallows you to manage GitHub directly from the terminal.
| Command | Example | Description | 
|---|---|---|
| gh auth login | Authenticate with a GitHub host to enable CLI commands to interact with your account | |
| gh auth login --with-token < mytoken.txt | Authenticate using a personal access token stored in a file ( | |
| gh auth login --hostname enterprise.internal | Authenticate against a GitHub Enterprise server (not github.com) | |
| gh repo clone | Clone a GitHub repository to your local machine | |
| gh repo clone user/repo | Clone the repository  | |
| gh repo clone cli/cli -- --depth=1 | Clone the repository but only download the latest commit for a faster, smaller clone | |
| gh repo clone cli/cli workspace/cli | Clone the repository into a custom folder  | |
| gh issue list | List issues in a GitHub repository, optionally filtered by various criteria | |
| gh issue list --assignee "@me" | List issues assigned to you | |
| gh issue list --state all | List issues regardless of state (open or closed) | |
| gh issue list --search "error no:assignee sort:created-asc" | List issues matching “error”, unassigned, sorted by creation date (ascending) | |
| gh pr create | Create a pull request on GitHub via the CLI | |
| gh pr create --title "..." | Create a pull request with the given title | |
| gh pr create --project "Roadmap" | Link the pull request to a GitHub project named “Roadmap” | |
| gh pr create --base develop --head monalisa:feature | Create a PR from branch  | |
| gh repo create | Create a new GitHub repository from the CLI | |
| gh repo create my-project | Create a new repository called  | |
| gh repo create my-project --public --clone | Create a public repository and clone it locally | |
| gh repo create my-project --private --source=. --remote=upstream | Create a private remote repository from the current folder and add a remote named  | 
💡 Git Aliases (Useful Shortcuts)
Set up convenient aliases to accelerate common Git commands:
git config --global alias.br branch                                       # shortcut for: git branch
git config --global alias.ci commit                                       # shortcut for: git commit
git config --global alias.co checkout                                     # shortcut for: git checkout
git config --global alias.graph "log --oneline --graph --all --decorate"  # pretty history graph
git config --global alias.last "log -1 HEAD"                              # show the last commit
git config --global alias.st status                                       # shortcut for: git status🚀 Advanced Git Commands for Professionals
| Command | Example | Description | 
|---|---|---|
| git filter-repo | A powerful and efficient tool for rewriting Git history to remove or modify files, authorship, or paths; replaces git filter-branchwith improved speed and safety | |
| git filter-repo --path secret.txt --invert-paths | Rewrite repository history to remove sensitive files or directories without the performance issues of  | |
| git filter-repo --replace-text replacements.txt | Bulk replace strings or patterns across the entire history (e.g., sanitise credentials) | |
| git filter-repo --subdirectory-filter src | Extract subdirectory history into a new repository, preserving commit metadata | |
| git worktree | Manage multiple working directories linked to a single repository, allowing concurrent work on different branches without cloning | |
| git worktree add ../feature feature-branch | Create an additional working tree attached to the same repository, enabling parallel branch checkouts without clones | |
| git worktree list | List all active worktrees, their paths, and associated branches | |
| git worktree remove ../feature | Remove a linked worktree when no longer required, cleaning up directories safely | |
| git replace | Create temporary references that replace existing objects, enabling non-destructive local history manipulation and testing | |
| git replace <old_commit> <new_commit> | Temporarily substitute one commit for another in your local repository — useful for testing or patching without rewriting history | |
| git replace --list | Show all active replacement references | |
| git replace -d <replace_ref> | Delete a specific replacement reference to revert behaviour | |
| git stash | Temporarily save uncommitted changes to a stack, allowing you to switch context without committing unfinished work | |
| git stash push -p | Interactively select hunks of changes to stash, providing fine-grained control over what is saved | |
| git stash push -m "WIP selective stash" | Create a stash with a custom message for easier identification | |
| git stash apply stash@{2} | Apply a specific stash from the stash list without dropping it | |
| git rebase | Reapply commits on top of another base tip, facilitating a cleaner, linear project history and interactive history editing | |
| git rebase --interactive --autosquash | Start an interactive rebase session that automatically reorders and squashes commits marked as fixup or squash, streamlining history cleanup | |
| git rebase -i --autosquash HEAD~10 | Automatically reorder and squash commits marked as fixup or squash before pushing, ensuring a tidy commit history | |
| git commit --fixup <commit> | Create a fix-up commit that will be auto-squashed during interactive rebase | |
| git commit --squash <commit> | Create a squash commit to combine with a specified commit during rebase | |
| git bisect | Binary search tool to identify the commit that introduced a bug by testing successive commits and narrowing down the faulty change | |
| git bisect run | Automate the bisect process by running a specified test script on each commit to identify the buggy commit without manual effort | |
| git bisect start; git bisect bad; git bisect good v1.0; git bisect run ./test.sh | Automate bisection with a test script, significantly speeding up bug identification | |
| git bisect visualize | Open a graphical tool to visualise the bisection process | |
| git bisect reset | Exit bisect mode and return to the original HEAD | |
| git commit | Record changes to the repository with advanced options for amend, sign, fixup, and message customisation, maintaining high-quality project history | |
| git commit --gpg-sign | Create a commit signed with your GPG key to ensure cryptographic verification of authenticity and authorship | |
| git commit -S -m "Signed commit" | Sign your commits with your GPG key to guarantee integrity and authorship verification | |
| git config --global user.signingkey <key_id> | Configure the GPG key used to sign commits globally | |
| git log --show-signature | Verify and display GPG signature information for commits | |
| git reflog | Maintain a log of updates to HEAD and branches, essential for recovering lost commits and understanding local history movements | |
| git reset --hard HEAD@{3} | Reset the current branch to a previous state from reflog to recover or undo changes | |
| git reflog expire --expire=now --all | Immediately expire all reflog entries, cleaning up reflog history (use with caution) | 
🧰 Pro Workflow Tips and Automation
| Topic | Commands / Example | Explanation & Pro Tips | 
|---|---|---|
| Aggressive Repository Clean-up | git gc --aggressive --prune=now | Performs deep garbage collection and prunes unreachable objects immediately to optimise the repository. Best used during maintenance windows | 
| Parallel Branch Worktrees | git worktree add ../feature-branch feature | Keep multiple working trees for simultaneous feature development, avoiding clone overhead | 
| Clean, Linear History | git rebase -i --autosquash | Before pushing, rebase interactively with autosquash to keep history clean and readable | 
| Secure Commits | git commit -S | Sign commits with GPG to enhance trustworthiness in shared repositories — mandatory in many enterprise environments | 
| Automated Bisecting | git bisect run ./test-script.sh | Automate bug hunting by running a test script on each candidate commit during bisect | 
| Conflict Resolution Cache | git config --global rerere.enabled true | Enable reuse of conflict resolutions to accelerate resolving repeated merge conflicts across rebases or merges | 
| Shared Aliases and Hooks | Store common Git aliases and commit hooks in a shared repository or CI pipeline to enforce team standards and improve productivity | 
Additional Resources
🧠 Tip
Do not try to memorise everything. Use --help, explore, and practise regularly:
git help <command>
git status🌐 Useful Links
📘 Official Git Documentation — detailed manual for all Git commands:
https://git-scm.com/docs
📙 Learn Git Branching — interactive visual tutorial to master branching concepts:
https://learngitbranching.js.org
📕 Pro Git Book (free, by Scott Chacon & Ben Straub):
https://git-scm.com/book
📗 Git Cheatsheet (official concise reference):
https://education.github.com/git-cheat-sheet-education.pdf