Git and Github

This resource provides comprehensive knowledge about basics of Git and GitHub as a beginer or Just a quick knowledge refresh.

Git and Github
Author
Materio
Listen

Git is a tool that helps you track changes in code (or any files) and work safely with others on the same project without overwriting each other’s work.

Simple idea

  • Git is a “version control system”: it remembers every change in your project, like a time machine for code.
  • You can go back to any earlier version, compare changes, and undo mistakes easily.
  • It is distributed: every developer has a full copy of the project history on their own computer, so it works even without internet.

Real-life analogy

  • Think of writing an important essay:
    • Without Git: you keep overwriting “final.docx”, and if something breaks, you’re stuck.
    • With Git: you save checkpoints (called commits) with messages like “added intro” or “fixed conclusion”, and you can jump back to any checkpoint.

Key concepts

  • Repository (repo): The project folder Git is tracking.
  • Commit: A snapshot of your files at some point in time, with a message.
  • Branch: A separate line of development to try new features without breaking the main code.
  • Merge: Combining changes from one branch into another.
  • Remote: An online copy of the repo (e.g., on GitHub, GitLab) used to share code with others.

Why students should care

  • Almost all serious software projects use Git, so it is expected in jobs and internships.
  • It saves time and stress:
    • Easy to recover from “I broke everything”.
    • Easy to see “who changed what and why”.
  • Great for group projects: everyone can work in parallel and then merge their work.

Setup Commands

CommandSyntaxWhat it does
Set namegit config --global user.name "Your Name"Tells Git what name to attach to your commits.
Set emailgit config --global user.email "you@example.com"Tells Git what email to attach to your commits.

Repository Commands

CommandSyntaxWhat it does
Initialize repogit initCreates a new hidden .git folder and starts tracking this directory with Git (but no files are committed yet).
Clone repogit clone <url>
Example: git clone https://github.com/user/project.git
Downloads the whole repo (files + history) from a server like GitHub.

Everyday Local Workflow

CommandSyntaxWhat it does
Check statusgit statusShows untracked files (new files Git doesn’t know yet), modified files, what is staged for the next commit. Use this frequently to know “where you are”.
Add specific filegit add <file>
Example: git add main.py
Moves changes from working directory to staging area, marking them for the next commit.
Add many filesgit add .Moves all changes from working directory to staging area (use carefully).
Commit changesgit commit -m "meaningful message"Saves a snapshot of all staged changes into the repo history.
Good habit: Use clear messages like "add login validation" rather than "changes".
See history (simple)git logShows previous commits, their IDs, authors, and messages.
See history (one-line)git log --onelineCompact view of commit history. Helpful for understanding what changed over time.

Working with Remotes (GitHub, GitLab)

CommandSyntaxWhat it does
Add remotegit remote add origin <url>
Example: git remote add origin https://github.com/user/project.git
Names that URL as origin (the default remote name).
First pushgit push -u origin mainSends your local commits to the remote so others (and you on another machine) can pull them.
Later pushesgit pushSame as first push after -u is set.
Pull updatesgit pullFetches new commits from the remote and merges them into your current branch.

Branching Basics

CommandSyntaxWhat it does
Create branchgit branch <branch-name>Creates a separate line of development so you can experiment without breaking main.
Switch branchgit checkout <branch-name>Switches to that branch.
Create + switchgit checkout -b <branch-name>
Example: git checkout -b feature-login
Creates and switches in one step (most common).
Merge branchgit checkout main
git merge feature-login
Combines the history and changes from feature-login into main.
If files were changed in both branches, you may get a merge conflict that you resolve manually, then git add and git commit.

Undo / Fix Situations

CommandSyntaxWhat it does
Discard changes in filegit checkout -- <file>
Example: git checkout -- main.py
Throws away unsaved edits in that file and restores it to the last committed version.
Unstage filegit reset <file>
Example: git reset main.py
Takes the file out of the staging area, but your edits remain in the working directory.
Diff (not staged)git diffShows line-by-line differences between current files and last commit.
Diff (staged)git diff --cachedShows differences between staged version and last commit.

Very Short Summary

ActionCommands
Start trackinggit init / git clone <url>
Check statusgit status
Stage changesgit add <file>
Save snapshotgit commit -m "message"
Send changesgit push
Get changesgit pull
Branchinggit checkout -b new-branch, git merge branch-name

Rollback and History Fixes

CommandSyntaxWhat it does
Undo last commit (keep changes)git reset --soft HEAD~1Removes the last commit, but keeps all changes staged for a new commit. Safe for "oops, wrong message".
Undo last commit (unstaged)git reset --mixed HEAD~1
(or just git reset HEAD~1)
Removes last commit AND unstages changes (they stay as uncommitted edits).
Undo last commit (discard changes)git reset --hard HEAD~1Removes last commit AND throws away all changes. DANGEROUS – use only if sure!
Undo commit but keep in historygit revert <commit-hash>Creates a NEW commit that undoes the changes of <commit-hash>. Safe for shared repos.
Go back to specific commitgit checkout <commit-hash>Puts you in "detached HEAD" mode (view old state). To make a branch: git checkout -b old-version.
See all commits (with hashes)git log --oneline --graphVisual tree of branches + short commit hashes. Copy hash for other commands.

Tip: HEAD~1 = 1 commit back, HEAD~2 = 2 commits back. Use git reflog to see all actions (even resets).


Delete Git History (Nuclear Options)

[!WARNING] These rewrite history. Never do on shared repos (breaks others). Use on personal repos only.

CommandSyntaxWhat it does
Delete entire history (keep files)git checkout --orphan temp
git add .
git commit -m "Fresh start"
git branch -D main
git branch -m main
git push -f origin main
Creates a new repo with current files, no history. Great for "start fresh".
Remove file from ALL historygit filter-branch --force --index-filter "git rm --cached --ignore-unmatch filename" --prune-empty --tag-name-filter cat -- --all
Then git push --force --all
Erases a sensitive file (API keys, passwords) from entire history. Use BFG Repo-Cleaner tool for big repos.
Squash all commits to onegit rebase -i --rootInteractive rebase: change "pick" to "squash" for all but first commit. Clean history for new repo.

Real-life: Use "orphan" for open-sourcing private code without history.


Custom Commit Metadata

CommandSyntaxWhat it does
Commit with custom authorgit commit -m "msg" --author="Fake Name <fake@email.com>"Overrides config for THIS commit only.
Commit with custom dateGIT_COMMITTER_DATE="2024-01-01T12:00:00" GIT_AUTHOR_DATE="2024-01-01T12:00:00" git commit -m "msg"Sets both author and committer dates. Useful for demos or fixing timestamps.
Change last commit's author/dategit commit --amend --author="New Name <new@email.com>" --date="2024-01-01T12:00"Rewrites the most recent commit's metadata.
Global date formatgit config --global log.date isoMakes git log show ISO dates everywhere (YYYY-MM-DD).

Fun trick: Backdate commits to make a perfect timeline for your resume!


What is GH CLI?

GitHub CLI (gh) is GitHub's official command-line tool. It extends Git with GitHub-specific features like creating issues/PRs, managing repos, and authenticating without a browser.

Why use it?

  • Faster workflows (no browser tabs).
  • Scripts/automation friendly.
  • Works with Git seamlessly.

Install (pick one):

Setup (first time only):

gh auth login
  • Choose "GitHub.com", HTTPS/SSH, browser/authenticate.
  • Now gh talks to your GitHub account!

Pro tip: Use gh auth status anytime to check login.


GH CLI Commands (GitHub Superpowers)

CommandSyntaxWhat it does
Create repogh repo create myproject --public --source=. --remote=origin --pushCreates GitHub repo from current local dir and pushes it.
Clone with issuesgh repo clone owner/repoClones repo + auto-opens GitHub page.
Create issuegh issue create --title "Bug" --body "Details"Quick issue without browser.
List issuesgh issue listShows your open issues/PRs.
Create PRgh pr create --title "Fix bug" --body "Changes"Creates PR from current branch.
Checkout PRgh pr checkout 123Downloads PR #123 as local branch.
Merge PRgh pr mergeMerges current branch PR (interactive).
View repogh repo viewOpens repo in browser.
Fork repogh repo forkForks current repo to your account.

Workflow example:

git checkout -b fix-bug
# make changes, git add/commit/push
gh pr create
# review/merge in browser or gh pr merge

Quick Git Setup (GitHub's Official Flow)

When GitHub creates a new repo, it shows these exact steps. Copy-paste them!

StepCommandsWhat it does
1. Create repo on GitHub(Do this in browser first: github.com/new)Makes empty repo on GitHub.
2. Local setupgit init
git branch -M main
Initializes local repo, renames default branch to main.
3. Connect to GitHubgit remote add origin https://github.com/username/new-repo.gitLinks your local repo to GitHub.
4. First commitgit add .
git commit -m "Initial commit"
Stages all files and makes first snapshot.
5. Push to GitHubgit push -u origin mainUploads your code + sets upstream tracking.

Full copy-paste sequence (after creating repo on GitHub):

git init
git branch -M main
git remote add origin https://github.com/YOURUSERNAME/YOURREPONAME.git
git add .
git commit -m "Initial commit"
git push -u origin main

Now you have a live GitHub repo in 30 seconds! 🎉