Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Git Documentation

Version control every developer uses — commits, branches, merge, rebase and GitHub collaboration.

Git is a distributed version control system: it records snapshots of your project over time, lets you go back to any version, work on features in parallel branches, and collaborate through hosts like GitHub, GitLab and Bitbucket. Every developer job expects Git.

1. Introduction & Installation

  • Windows: git-scm.com (includes Git Bash).
  • macOS: xcode-select --install or brew install git. Linux: sudo apt install git.

Configure your identity once (it's written into every commit):

git --version
git config --global user.name "Asha Rao"
git config --global user.email "asha@example.com"
git config --global init.defaultBranch main
git config --global core.editor "code --wait"
git config --list

Three places to keep in mind:

Working directory  --git add-->  Staging area (index)  --git commit-->  Repository (.git history)

⚠️ Common error: Author identity unknown — Please tell me who you are — set user.name and user.email as above.

2. Basic Workflow

git init -q demo && cd demo
echo "# Demo" > README.md
git status --short
git add README.md
git status --short
git commit -q -m "Add README"
git log --oneline | wc -l

Output:

?? README.md
A  README.md
1

?? = untracked, A = added to the staging area, M = modified. Useful variants:

git add .                     # stage everything in the current folder
git add -p                    # stage chosen parts of files interactively
git commit -am "Fix typo"     # stage tracked files + commit in one step
git diff                      # unstaged changes
git diff --staged             # staged changes (what will be committed)
git log --oneline --graph --all

⚠️ Common error: committing secrets or huge folders. Create a .gitignore before the first commit (node_modules/, .env, dist/, *.log).

3. Commits & History

A commit is a snapshot with an id (SHA hash), author, date, message and a pointer to its parent commit(s).

git init -q history && cd history
for f in a b c; do echo "$f" > "$f.txt"; git add "$f.txt"; git commit -q -m "Add $f"; done
git log --format="%s"
git log --format="%s" -1 HEAD~1
git show --stat --format="%s" HEAD | head -3

Output:

Add c
Add b
Add a
Add b
Add c

 c.txt | 1 +

Good commit messages: short imperative summary (≤ 50 chars) like "Add login rate limit", then a blank line and details if needed. Conventional Commits style: feat: ..., fix: ..., docs: ....

Search history: git log --author="Asha", git log -S "functionName" (when a string was added/removed), git blame file.js (who changed each line).

4. Branches

A branch is a lightweight movable pointer to a commit. Create one for every feature or fix.

git init -q branching && cd branching
echo "v1" > app.txt && git add . && git commit -q -m "v1"
git switch -q -c feature/login        # create + switch (older: git checkout -b)
echo "login" > login.txt && git add . && git commit -q -m "Add login"
git branch
git switch -q main
ls

Output:

* feature/login
  main
app.txt

login.txt disappears on main because it only exists on the feature branch. Other commands: git branch -d name (delete merged branch), git branch -m new-name (rename), git switch - (previous branch).

5. Merging & Conflicts

git init -q merging && cd merging
echo "v1" > app.txt && git add . && git commit -q -m "v1"
git switch -q -c feature
echo "feature work" > feature.txt && git add . && git commit -q -m "Feature"
git switch -q main
git merge -q feature                  # fast-forward: main simply moves forward
ls
git log --format="%s"

Output:

app.txt
feature.txt
Feature
v1

A conflict happens when both branches changed the same lines:

git init -q conflict && cd conflict
echo "colour = blue" > config.txt && git add . && git commit -q -m "base"
git switch -q -c theme && echo "colour = green" > config.txt && git commit -q -am "green"
git switch -q main && echo "colour = red" > config.txt && git commit -q -am "red"
git merge theme > /dev/null
cat config.txt

Output:

<<<<<<< HEAD
colour = red
=======
colour = green
>>>>>>> theme

To resolve: edit the file to the final content (remove the markers), then git add config.txt and git commit. Abort with git merge --abort.

⚠️ Common error: committing files that still contain <<<<<<< markers. Search for them before committing (git diff --check).

6. Remotes & GitHub

git remote add origin https://github.com/asha/codify-notes.git
git remote -v
git push -u origin main         # first push: -u sets the upstream
git push                        # later pushes
git pull                        # fetch + merge (or rebase) from the remote
git fetch                       # download new commits without changing your files
git clone https://github.com/asha/codify-notes.git

Authentication: GitHub needs a Personal Access Token or SSH key instead of a password (ssh-keygen -t ed25519, add the public key in GitHub → Settings → SSH keys). Install the GitHub CLI (gh auth login) to make this easy.

Pull request workflow (team standard):

  1. git switch -c feature/search from an up-to-date main.
  2. Commit small, focused changes; git push -u origin feature/search.
  3. Open a Pull Request on GitHub, get a review, fix comments, merge.
  4. git switch main && git pull and delete the branch.

⚠️ Common error: ! [rejected] main -> main (fetch first) — the remote has commits you don't have. Run git pull (resolve conflicts if any), then push again. Never --force on shared branches.

7. Undoing Changes

git init -q undo && cd undo
echo "good" > f.txt && git add . && git commit -q -m "good"
echo "oops" > f.txt
git restore f.txt                    # discard unstaged changes in the working directory
cat f.txt
echo "staged oops" > f.txt && git add f.txt
git restore --staged f.txt           # unstage (keeps the change in the file)
git status --short

Output:

good
 M f.txt
Situation Command
Change the last commit message / add a forgotten file git commit --amend
Undo a commit that is already pushed git revert <sha> (new commit that reverses it)
Move the branch back, keep changes in files git reset --soft HEAD~1 / git reset HEAD~1
Throw away commits and changes (dangerous) git reset --hard HEAD~1
Find "lost" commits after a reset git reflog
Save unfinished work temporarily git stash, later git stash pop
git init -q revert && cd revert
echo 1 > n.txt && git add . && git commit -q -m "one"
echo 2 > n.txt && git commit -q -am "two"
git revert --no-edit HEAD > /dev/null
cat n.txt
git log --format="%s" | head -1

Output:

1
Revert "two"

⚠️ Common error: git reset --hard on commits you already pushed rewrites shared history. Use git revert for anything others may have pulled.

8. Rebase, Stash & Cherry-pick

Rebase replays your commits on top of another branch — a straight, linear history:

git switch feature/search
git rebase main                 # move feature commits on top of the latest main
# on conflict: fix files, git add, git rebase --continue   (or --abort)
git rebase -i HEAD~3            # interactive: squash, reword, reorder the last 3 commits

Golden rule: never rebase commits that others have already pulled (it rewrites their ids).

Stash shelves uncommitted work:

git init -q stash && cd stash
echo "base" > a.txt && git add . && git commit -q -m "base"
echo "work in progress" >> a.txt
git stash -q
cat a.txt
git stash pop -q
tail -1 a.txt

Output:

base
work in progress

Cherry-pick copies one commit onto the current branch: git cherry-pick <sha> — handy for applying a hotfix to a release branch.

9. Tags, .gitignore & Configuration

git tag -a v1.0.0 -m "First release"   # annotated tag for releases
git push origin v1.0.0
git tag                                 # list tags

.gitignore patterns:

node_modules/
dist/
.env
*.log
!keep.log          # exception: do track this file
**/temp/
git init -q ignore && cd ignore
printf "node_modules/\n.env\n" > .gitignore
mkdir node_modules && touch node_modules/x.js .env app.js
git status --short

Output:

?? .gitignore
?? app.js

Already-tracked files aren't ignored retroactively — remove them from the index: git rm --cached .env.

Helpful aliases:

git config --global alias.st "status -sb"
git config --global alias.lg "log --oneline --graph --decorate --all"

10. Advanced Concepts

  • How Git stores data: objects (blobs = file contents, trees = folders, commits, tags) addressed by their SHA hash; branches are files containing a commit id; HEAD points to the current branch.
  • git bisect: binary-search history to find the commit that introduced a bug (git bisect start, bad, good <sha>, repeat).
  • Workflows: GitHub Flow (short feature branches + PRs to main), Git Flow (develop/release/hotfix branches), trunk-based development.
  • Hooks: scripts in .git/hooks (or managed with Husky) that run lint/tests before commits or pushes.
  • Large files: Git LFS stores big binaries outside the repository.
  • Submodules / subtrees: include another repository inside yours.
  • Signing: git commit -S with GPG or SSH keys for verified commits.
  • Worktrees: git worktree add ../hotfix main — check out another branch in a second folder at the same time.
git init -q internals && cd internals
echo "hello" > a.txt && git add a.txt
git cat-file -t "$(git hash-object a.txt)"
git cat-file -p "$(git hash-object a.txt)"
cat .git/HEAD

Output:

blob
hello
ref: refs/heads/main

11. Examples with Output

Example 1 — Count commits per author

git init -q authors && cd authors
for i in 1 2; do echo $i > f$i; git add .; git -c user.name=Asha -c user.email=a@x.com commit -q -m "c$i"; done
echo 3 > f3; git add .; git -c user.name=Ravi -c user.email=r@x.com commit -q -m "c3"
git shortlog -sn HEAD
     2	Asha
     1	Ravi

Example 2 — See which files changed between two commits

git init -q diffs && cd diffs
echo a > a.txt && git add . && git commit -q -m "first"
echo b > b.txt && echo a2 >> a.txt && git add . && git commit -q -m "second"
git diff --name-status HEAD~1 HEAD
M	a.txt
A	b.txt

Example 3 — Squash a feature into one commit on main

git init -q squash && cd squash
echo base > f && git add . && git commit -q -m "base"
git switch -q -c feature
for i in 1 2 3; do echo $i >> f; git commit -q -am "wip $i"; done
git switch -q main
git merge --squash feature > /dev/null
git commit -q -m "Add feature (squashed)"
git log --format="%s"
Add feature (squashed)
base

12. Practice Problems

  1. Create a repository, add a README and .gitignore, and make three meaningful commits.
  2. Create a feature branch, commit to it, and merge it into main with a merge commit (--no-ff).
  3. Create a merge conflict on purpose and resolve it.
  4. Push your project to a new GitHub repository and open a pull request from a branch.
  5. Use git stash to switch branches in the middle of work, then restore it.
  6. Undo a pushed commit with git revert; undo a local commit with git reset --soft.
  7. Clean up a messy branch with git rebase -i (squash "wip" commits).
  8. Use git bisect to find the commit that broke a test in a small project.

13. Interview Questions

1. What is the difference between Git and GitHub? Git is the version control tool on your computer; GitHub is a hosting service for Git repositories with collaboration features (PRs, issues, Actions).

2. git fetch vs git pull? fetch downloads new commits without changing your branch; pull = fetch + merge (or rebase) into your current branch.

3. Merge vs rebase? Merge combines histories with a merge commit (preserves context); rebase replays commits on top of another branch for a linear history (rewrites commit ids).

4. What is the staging area? An intermediate area where you choose exactly which changes go into the next commit.

5. git reset vs git revert? reset moves the branch pointer back (rewrites history — local use); revert creates a new commit that undoes a previous one (safe for shared history).

6. What is HEAD? A pointer to the commit/branch you currently have checked out. "Detached HEAD" means it points to a commit, not a branch.

7. How do you resolve a merge conflict? Open the conflicted files, choose/edit the final content, remove the conflict markers, git add the files and commit (or continue the rebase).

8. What is a fast-forward merge? When the target branch has no new commits, Git just moves its pointer forward — no merge commit is needed.

9. What does git stash do? Saves uncommitted changes on a stack and cleans the working directory; git stash pop reapplies them.

10. How do you remove a file from Git but keep it locally? git rm --cached <file>, then add it to .gitignore.

14. Cheat Sheet & References

Setup and basics

# configure once
git config --global user.name "Name"
git config --global user.email "you@example.com"
git init
git clone <url>
git status
git add <file>
git add .
git commit -m "message"
git log --oneline --graph

Branches

git branch
git switch -c feature/x
git switch main
git merge feature/x
git branch -d feature/x
git rebase main

Remote

git remote add origin <url>
git push -u origin main
git pull
git fetch --all --prune
git push origin --delete old-branch

Undo

git restore <file>
git restore --staged <file>
git commit --amend
git revert <sha>
git reset --soft HEAD~1
git stash
git stash pop
git reflog

Inspect

git diff
git diff --staged
git show <sha>
git blame <file>
git log -p -- <file>
git shortlog -sn

Official documentation