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
Materio
Listen
0

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

Command Syntax What it does
Set name git config --global user.name "Your Name" Tells Git what name to attach to your commits.
Set email git config --global user.email "you@example.com" Tells Git what email to attach to your commits.

Repository Commands

Command Syntax What it does
Initialize repo git init Creates a new hidden .git folder and starts tracking this directory with Git (but no files are committed yet).
Clone repo git 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

Command Syntax What it does
Check status git status Shows 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 file git add <file>
Example: git add main.py
Moves changes from working directory to staging area, marking them for the next commit.
Add many files git add . Moves all changes from working directory to staging area (use carefully).
Commit changes git 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 log Shows previous commits, their IDs, authors, and messages.
See history (one-line) git log --oneline Compact view of commit history. Helpful for understanding what changed over time.

Working with Remotes (GitHub, GitLab)

Command Syntax What it does
Add remote git 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 push git push -u origin main Sends your local commits to the remote so others (and you on another machine) can pull them.
Later pushes git push Same as first push after -u is set.
Pull updates git pull Fetches new commits from the remote and merges them into your current branch.

Branching Basics

Command Syntax What it does
Create branch git branch <branch-name> Creates a separate line of development so you can experiment without breaking main.
Switch branch git checkout <branch-name> Switches to that branch.
Create + switch git checkout -b <branch-name>
Example: git checkout -b feature-login
Creates and switches in one step (most common).
Merge branch git 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

Command Syntax What it does
Discard changes in file git checkout -- <file>
Example: git checkout -- main.py
Throws away unsaved edits in that file and restores it to the last committed version.
Unstage file git 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 diff Shows line-by-line differences between current files and last commit.
Diff (staged) git diff --cached Shows differences between staged version and last commit.

Very Short Summary

Action Commands
Start tracking git init / git clone <url>
Check status git status
Stage changes git add <file>
Save snapshot git commit -m "message"
Send changes git push
Get changes git pull
Branching git checkout -b new-branch, git merge branch-name

Rollback and History Fixes

Command Syntax What it does
Undo last commit (keep changes) git reset --soft HEAD~1 Removes 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~1 Removes last commit AND throws away all changes. DANGEROUS – use only if sure!
Undo commit but keep in history git revert <commit-hash> Creates a NEW commit that undoes the changes of <commit-hash>. Safe for shared repos.
Go back to specific commit git 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 --graph Visual 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.

Command Syntax What 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 history git 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 one git rebase -i --root Interactive 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

Command Syntax What it does
Commit with custom author git commit -m "msg" --author="Fake Name <fake@email.com>" Overrides config for THIS commit only.
Commit with custom date GIT_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/date git commit --amend --author="New Name <new@email.com>" --date="2024-01-01T12:00" Rewrites the most recent commit's metadata.
Global date format git config --global log.date iso Makes 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)

Command Syntax What it does
Create repo gh repo create myproject --public --source=. --remote=origin --push Creates GitHub repo from current local dir and pushes it.
Clone with issues gh repo clone owner/repo Clones repo + auto-opens GitHub page.
Create issue gh issue create --title "Bug" --body "Details" Quick issue without browser.
List issues gh issue list Shows your open issues/PRs.
Create PR gh pr create --title "Fix bug" --body "Changes" Creates PR from current branch.
Checkout PR gh pr checkout 123 Downloads PR #123 as local branch.
Merge PR gh pr merge Merges current branch PR (interactive).
View repo gh repo view Opens repo in browser.
Fork repo gh repo fork Forks 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!

Step Commands What it does
1. Create repo on GitHub (Do this in browser first: github.com/new) Makes empty repo on GitHub.
2. Local setup git init
git branch -M main
Initializes local repo, renames default branch to main.
3. Connect to GitHub git remote add origin https://github.com/username/new-repo.git Links your local repo to GitHub.
4. First commit git add .
git commit -m "Initial commit"
Stages all files and makes first snapshot.
5. Push to GitHub git push -u origin main Uploads 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! 🎉