1. What does `git add` do? What’s the staging area?
`git add` places changes into the index (staging area), a buffer where you curate what will go into the next commit.
Get the Preplance app for a seamless learning experience. Practice offline, get daily streaks, and stay ahead with real-time interview updates.
Get it on
Google Play
4.9/5 Rating on Store
TCS · Git & Version Control
Practice Git & Version Control questions specifically asked in TCS interviews – ideal for online test preparation, technical rounds and final HR discussions.
Questions
83
Tagged for this company + subject
Company
TCS
View company-wise questions
Subject
Git & Version Control
Explore topic-wise practice
Go through each question and its explanation. Use this page for targeted revision just before your TCS Git & Version Control round.
`git add` places changes into the index (staging area), a buffer where you curate what will go into the next commit.
For complete preparation, combine this company + subject page with full company-wise practice and subject-wise practice. You can also explore other companies and topics from the links below.
Use `git branch --set-upstream-to=<remote>/<branch>` from the local branch. Alternatively, the first push can set it: `git push --set-upstream origin <branch>`.
Use `-d` for safe deletion (already merged). `git fetch --prune` cleans stale remote-tracking refs.
`git restore <path>` replaces the file from HEAD (modern replacement for `checkout --`).
`-S` signs the commit. Configure with `user.signingkey` and GPG agent beforehand.
`--autosquash` pairs `fixup!`/`squash!` commits with their targets in the todo list.
Create a branch (`git switch -c`) if you intend to keep commits.
Squash condenses all PR commits into one for a tidy history.
This combo visualizes branch tips and relationships succinctly across all refs.
A remote is a named reference to another copy of the repository, typically hosted on a server. 'origin' is the default name Git assigns when you clone, pointing back to the source repository. It lets you fetch, pull, and push changes for collaboration.
Modern Git: `git switch -c <name>` creates and checks out. Classic equivalent: `git checkout -b <name>`.
`git stash` saves local modifications (tracked files) for later: use `stash pop/apply` to restore.
Enable with `git config rerere.enabled true` to speed repeated merges/rebases with identical conflicts.
Squash yields a single commit; good for tidy history, but loses granular commit info.
Git is a distributed version control system (DVCS) created by Linus Torvalds for fast, reliable source control. It enables branching/merging, offline work, and full history on every clone—ideal for team collaboration and safe iteration.
'.gitignore' tells Git which files/paths not to track (e.g., builds, secrets). Common patterns: 'node_modules/' and '*.log'. This keeps history clean and avoids committing noise or sensitive data.
# .gitignore node_modules/ *.log .DS_Store /dist/
`status` summarizes tracked/untracked/staged; `diff` shows content differences.
A commit is a snapshot of staged changes with metadata (hash, author, time). Clear messages explain intent, aid code review, and improve traceability.
`origin` is the default remote alias created by `git clone`.
Branches let you isolate work (features, fixes, experiments) without disrupting the main line. In Git, branches are lightweight pointers to commits, so creating/switching is fast and storage-efficient.
`git merge <branch>` integrates that branch into the current HEAD.
`git cherry-pick <hash>` applies the changes from a specific commit onto the current branch. Commonly used to backport a hotfix commit from `main` to a release branch without merging all other changes.
`revert` creates a new commit that negates the changes without rewriting history, safe for shared branches.
`pull --rebase` rewrites local work on top of fetched commits, avoiding a merge commit for a linear history.
`git add -p` lets you review and stage hunks interactively for granular commits.
Stage the missing change, then amend to rewrite the tip commit (avoid on public history).
`restore --staged` removes from Index only; the file contents remain in the working tree.
`--staged` (aka `--cached`) shows Index vs HEAD; plain `git diff` shows WT vs Index.
`pull` first fetches remote tracking changes then integrates them, while `fetch` only updates remote-tracking refs.
`--prune` deletes local stale remote-tracking branches (e.g., origin/feature-x) removed from the remote.
`--depth 1` creates a shallow clone with truncated history for speed and reduced size.
A submodule embeds another repo at a specific commit. After cloning, run `git submodule init` then `git submodule update` (or `git submodule update --init --recursive`) to fetch and checkout submodule contents.
`--no-ff` creates a merge commit even if HEAD could fast-forward, keeping branch context for later tracing/reverts.
Use it to transplant a range of commits onto a different base, skipping earlier ones. Example: move `featureA` commits that diverged from `topic` onto `main`: `git rebase --onto main topic featureA`.
An octopus merge merges more than two branches in a single commit. It’s suitable for merging many independent topic branches without conflicts; avoid when manual conflict resolution is required.
Rebasing avoids merge bubbles, and squashing yields a single, reviewed commit per PR while PR metadata preserves context.
Working tree = your files on disk; index = staged snapshot for the next commit; HEAD = pointer to the last commit of the current branch. Most history edits move HEAD; file-level fixes move working tree or index.
`revert` adds a new commit that negates a past one; safe for shared branches.
Revert creates a new inverse commit, preserving subsequent history.
Use `git revert --no-commit A^..B` to stage inverse changes for the range, review, then `git commit` once. Or `git revert A^..B` to create multiple revert commits.
Branches isolate work so features, fixes, and experiments can proceed without impacting the main line. They allow concurrent workflows, easier code review via PRs, and controlled integration back to trunk.
If no divergence exists, Git advances the pointer (no merge commit).
Merge preserves history with a merge commit—good for shared branches. Rebase rewrites the feature to sit atop main—clean linear history, ideal before opening a PR. Avoid rebasing public branches.
Policy: feature branches rebase onto latest main; PRs merge with squash or rebase-merge; disallow merge commits on main. Steps: `git fetch`, `git rebase origin/main`, resolve, push with `--force-with-lease`, then squash-merge PR.
Octopus merges combine multiple heads, usually for automated, conflict-free integrations.
Stash lets you temporarily shelve uncommitted changes so you can switch branches, pull fixes, or review code with a clean tree. Later you reapply the changes, avoiding throwaway commits or losing work.
Branches isolate work (features, fixes, experiments), keep main stable, enable review and CI per branch, and simplify rollback/cleanup without risking production code.
`--all` (aka `-a`) includes ignored and untracked files along with tracked changes.
`-d` removes untracked directories; `-f` is required to actually perform deletion.
Git Flow uses persistent main and develop branches; feature/release/hotfix are short-lived.
Clear title, description (problem, approach, scope), links to issues/tickets, screenshots/logs, test notes, checklist, and small, focused commits.
Draft PRs invite early review without merge intent.
They’re easier to review, reduce cycle time, lower defect risk, improve merge success, and aid revertability.
Keywords like “Fixes/Closes/Resolves #id” close the issue on merge to default branch.
`squash` merges commits and lets you edit a combined message; `fixup` discards the later message.
`--signoff` appends a DCO sign-off line to the commit message.
`git reflog` shows previous HEAD positions. Identify the lost commit or pre-rebase state and `git reset --hard <hash>` or create a new branch from it to recover.
Tags mark important points in history (e.g., releases). Annotated tags store metadata (tagger, date, message, signature) and are ideal for official releases; lightweight tags are simple pointers for personal bookmarks.
Pushing a specific tag uses `git push <remote> <tag>`; `--tags` pushes all tags.
MAJOR → incompatible, MINOR → new compatible features, PATCH → bug fixes.
Highlights, breaking changes, migration steps, bug fixes, known issues, contributors, and links to diffs/PRs. Keep crisp and user-centric.
Use SemVer for GA (e.g., vX.Y.Z), suffix `-rc.N`/`-beta.N` for candidates, `-hotfix.N` for urgent patches, and build metadata for CI artifacts. Protect tags, sign GA tags, auto-generate notes via CI.
Interactively rebase the feature branch onto the latest main and squash noisy merges into logical commits. This yields a linear, readable history while preserving meaningful changes. Avoid rewriting history only after the branch is shared publicly unless teammates agree.
Actionable comments (specific, respectful), checks for correctness & security, and validation via passing CI/tests. Keep scope focused, request changes with rationale, and approve only when standards are met.
Structured context improves review quality and deploy safety.
Early collaboration reduces rework and aligns on approach.
Enforce squash to keep a clean, one-commit-per-PR history and easy revert. Trade-offs: lose granular interim commits and bisect fidelity; mitigate by writing a thorough squash message and linking PR.
List with `git stash list`. Inspect with `git stash show -p stash@{n}` to see the patch, or `git show stash@{n}` for full object details.
The Index is a middle layer between your working tree and the repository. You choose exactly which changes to include in the next snapshot (commit), enabling partial commits and clean, reviewable history.
`git init` bootstraps a repository in the current folder; `git clone` fetches an existing repo, files, branches, and history.
Edit to resolve, stage resolved files, then commit. During rebase, you’d use `git rebase --continue` after `git add`.
Pushing an empty ref (`:<name>`) deletes the remote branch. Modern alternative: `git push origin --delete feature/login`.
Lightweight tags are simple pointers to a commit. Annotated tags (`git tag -a`) store metadata (tagger, date, message, GPG sig). Use annotated tags for releases; lightweight tags for local/bookmark usage.
Git Flow favors release cycles (develop, release, hotfix) for products with scheduled releases. GitHub Flow suits continuous delivery with short-lived feature branches and PRs to main. Trunk-based emphasizes committing to main behind flags with tiny branches for rapid integration. Choose based on cadence, compliance, and team size.
Squash merge maintains a clean history with one commit representing the PR.
`--hard` aligns index and working tree to the target commit; untracked files remain unless cleaned.
Rotate the secret. Use `git filter-repo` (or BFG) to purge the file/paths from all commits, force-push with lease, invalidate caches, and update PRs. Add patterns to `.gitignore` to prevent recurrence.
`pop = apply + drop`. Use `apply` to reuse later, `pop` to consume once.
1) Commit or stash WIP (`git stash -p -m "wip"`). 2) Verify status (`git status`, `git stash list`). 3) Clean dry-run (`git clean -ndx`). 4) If OK, run `git clean -fdx` for a pristine tree. 5) Reapply stashed pieces as needed with `git stash apply` and re-stage.
Rebase replays commits from your branch onto a new base, creating new commit IDs and a linear history. It’s a rewrite; the old commits are replaced by equivalent ones atop the target base.
Resolve conflicts, `git add`, then `--continue`; use `--abort` to return to pre-rebase state.
Automate SemVer bumps on protected branch and create annotated (optionally signed) tags with release notes.
GitHub Flow (trunk-based: small feature branches → PR → merge to main → deploy) fits products that deploy very frequently and value simplicity. Git Flow (long-lived develop, release/hotfix branches) suits scheduled releases and heavier QA gates. Choose the simplest model that matches release cadence and compliance needs.