Git and GitHub Interview Questions and Answers (90+)
101 Git and GitHub interview questions with commands: rebase, reset vs revert, reflog recovery, rulesets, CODEOWNERS, Actions and real scenarios.
This page has 101 Git and GitHub interview questions, grouped from basics to real-world scenarios. Freshers can start with the basics and branching sections. Engineers with two or more years of experience should spend more time on history rewriting, recovery, GitHub governance and the scenario questions at the end. Each answer gives the short version first, then a command.
If you want the bigger picture of how teams run repositories day to day, read our Git repository management best practices alongside this list. For the full set of DevOps topics, see the DevOps interview questions hub.
Key takeaways
- Interviewers rarely stop at definitions. Expect follow-ups like "how would you undo that after pushing?"
- Know three comparisons cold: merge vs rebase, reset vs revert vs restore, and fetch vs pull. Tables for all three are below.
- Learn the modern commands: git switch and git restore split up the old git checkout, and --force-with-lease is the safer way to force push.
- Almost nothing committed is truly lost. git reflog is the answer to most recovery questions.
- For GitHub roles, know branch protection, rulesets, CODEOWNERS, required checks, Actions security (OIDC, GITHUB_TOKEN permissions), Dependabot and push protection.
- Commands in this guide follow the current Git reference on git-scm.com and GitHub Docs.
Git basics (freshers)
1. What is Git, and how is it different from GitHub?
Git is a distributed version control system that runs on your machine and records the history of your files. GitHub is a hosting service built around Git. It adds pull requests, issues, code review, Actions for CI/CD and security features. You can use Git without GitHub (with GitLab, Bitbucket, Azure Repos or a plain server), but GitHub needs Git.
2. What does "distributed" mean, and how is Git different from SVN?
In Git every clone holds the full history, so you can commit, branch, view logs and diff without a network connection. SVN is centralised: history lives on one server and most operations need it. Branching in Git is cheap because a branch is just a pointer to a commit, while in SVN a branch is a copy of a directory on the server.
3. What are the working tree, the staging area and the repository?
The working tree is the files you edit. The staging area (also called the index) holds the snapshot you are preparing for the next commit. The repository (the .git directory) stores commits and all other objects. Changes move from working tree to index with git add, and from index to repository with git commit.
4. What is the difference between git init and git clone?
git init creates a new, empty repository in the current folder. git clone copies an existing repository, including its full history, sets up a remote called origin and checks out the default branch.
git init my-app
git clone https://github.com/org/my-app.git
5. What is a commit, and what does it contain?
A commit is a snapshot of the project at one point in time. Internally it is an object that points to a tree (the directory snapshot), to its parent commit or commits, and stores the author, committer, timestamps and message. Its ID is a hash of all that content, so changing anything produces a different commit ID.
6. How does Git protect the integrity of history?
Every object (blob, tree, commit, tag) is addressed by a hash of its content. Because each commit includes its parent's hash, changing an old commit changes every hash after it, which is easy to detect. Git uses a hardened SHA-1 by default and also supports a SHA-256 object format for new repositories; check that your hosting platform supports it before using it.
git cat-file -p HEAD # show the raw commit object
git init --object-format=sha256 new-repo
7. What is the difference between git add and git commit?
git add copies changes into the staging area. git commit saves whatever is staged as a new commit. Because they are separate, you can stage only part of your work. git add -p lets you pick individual hunks.
git add -p src/app.py
git commit -m "Fix timeout handling in payment client"
8. What does git status show?
It shows the current branch, how it compares with its upstream, and which files are staged, modified or untracked. git status -s gives a two-column short format: the left column is the index, the right column is the working tree.
9. What is .gitignore, and why does it not work for a file I already committed?
.gitignore lists patterns for untracked files that Git should not offer to add, such as build output, logs and node_modules/. It has no effect on files that are already tracked. To stop tracking such a file, remove it from the index and keep it on disk.
echo "config/local.env" >> .gitignore
git rm --cached config/local.env
git commit -m "Stop tracking local env file"
10. What are the configuration levels in Git?
Git reads system (--system), global or user (--global), local or repository (--local) and worktree (--worktree) settings. More specific levels override broader ones, so a repository setting beats your global one. --show-origin tells you which file a value came from.
git config --global user.name "Your Name"
git config --local user.email "[email protected]"
git config --list --show-origin
11. What is HEAD?
HEAD is a reference to what you currently have checked out. Normally it points to a branch name, which in turn points to a commit. HEAD~1 means the first parent of the current commit, and HEAD~3 goes three commits back.
12. How do you see what changed with git diff?
git diff compares the working tree with the index (unstaged changes). git diff --staged compares the index with HEAD (what will be committed). You can also compare branches or commits.
git diff
git diff --staged
git diff main...feature/login # changes on the feature branch since it forked from main
13. Which git log options are useful in practice?
--oneline --graph --all draws the branch structure. -p shows patches, --author filters by person, -- path limits to a file, and -S (the pickaxe) finds commits that added or removed a string.
git log --oneline --graph --all
git log -S "MAX_RETRIES" -- src/
git log --since="2 weeks ago" --author="Your Name"
14. What is git blame used for?
git blame shows, line by line, the last commit that changed each line. Use -L to limit the range. If a big formatting commit pollutes the output, list it in a .git-blame-ignore-revs file and pass it with --ignore-revs-file; GitHub's blame view also honours that file.
git blame -L 40,60 src/payment.py
15. How do you change the last commit?
git commit --amend replaces the last commit with a new one that includes anything you staged and, optionally, a new message. It creates a new commit ID, so only amend commits you have not pushed to a shared branch.
git add forgotten_file.py
git commit --amend --no-edit
16. What is a tag, and what is the difference between lightweight and annotated tags?
A tag is a fixed name for a commit, usually a release. A lightweight tag is just a pointer. An annotated tag is a full object with tagger, date and message, and it can be signed. Use annotated tags for releases. Tags are not pushed by default.
git tag -a v1.4.0 -m "Release 1.4.0"
git push origin v1.4.0
17. How do git rm and git mv work?
git rm deletes a file and stages the deletion; git rm --cached stages the deletion but keeps the file on disk. git mv renames a file and stages the change. Git does not store renames as such; it detects them by comparing content.
18. What is .gitattributes used for?
.gitattributes assigns attributes to paths. Common uses are line-ending normalisation, marking files as binary, custom diff or merge drivers, and the filters used by Git LFS. Since it is committed, everyone on the team gets the same behaviour, unlike core.autocrlf which is a personal setting.
# .gitattributes
* text=auto
*.sh text eol=lf
*.png binary
19. What is Git LFS, and when would you use it?
Git Large File Storage replaces large binary files (videos, design files, datasets) with small pointer files in the repository and stores the real content on a separate LFS server. Clones stay small and fast. It is an extension, so it must be installed on each machine.
git lfs install
git lfs track "*.psd"
git add .gitattributes design/banner.psd
git commit -m "Track design files with LFS"
Branching and merging
20. What is a branch internally?
A branch is a movable pointer to a commit, stored as a reference under refs/heads/ (as a small file or inside .git/packed-refs). When you commit on a branch, Git moves that pointer to the new commit. That is why creating a branch is instant.
21. What is the difference between git switch and git checkout?
git checkout does two unrelated jobs: switching branches and restoring files. Git 2.23 split these into git switch (branches) and git restore (files). git checkout still works, but the newer commands make intent clearer and are harder to misuse.
git switch -c feature/login # create and switch
git switch main
git switch - # back to the previous branch
22. How do you list, rename and delete branches?
git branch lists local branches, -r remote-tracking ones and -a both. git branch -m renames. -d deletes only if the branch is merged into its upstream or HEAD; -D forces deletion.
git branch -m old-name new-name
git branch -d feature/done
git branch -D experiment/throwaway
23. What is a fast-forward merge versus a three-way merge?
If the target branch has no new commits since the feature branch started, Git just moves the pointer forward: a fast-forward, with no merge commit. If both branches have new commits, Git does a three-way merge using the common ancestor and creates a merge commit with two parents. --no-ff forces a merge commit; --ff-only refuses anything that is not a fast-forward.
git merge --no-ff feature/login
git merge --ff-only origin/main
24. Which merge strategies does Git have?
The default for merging one branch is ort. Since Git 2.50, recursive is just another name for ort. octopus merges more than two branches, ours records a merge but keeps only the current branch's content, and subtree handles merging a project into a subdirectory. Do not confuse -s ours (strategy) with -X ours (an option that only prefers our side in conflicting hunks).
git merge -X theirs feature/config # resolve conflicting hunks in favour of the other branch
git merge -s ours legacy-branch # record the merge, keep current content
25. How do you resolve a merge conflict?
Run git status to see conflicted files, edit each one to remove the conflict markers and keep the correct code, then stage and commit. If it goes wrong, git merge --abort returns you to the state before the merge.
<<<<<<< HEAD
timeout = 30
=======
timeout = 45
>>>>>>> feature/config
git add config.py
git commit
26. How can you make conflicts easier to read?
Set merge.conflictStyle to zdiff3. The markers then also show the original version from the common ancestor, so you can see what each side actually changed. git mergetool opens a configured visual tool.
git config --global merge.conflictStyle zdiff3
27. What is git rerere?
rerere means "reuse recorded resolution". Once enabled, Git remembers how you resolved a conflict and applies the same resolution automatically when the identical conflict appears again, which helps with long-running branches that you rebase repeatedly.
git config --global rerere.enabled true
28. What is the difference between merge and rebase?
Both bring changes from one branch into another. Merge keeps history exactly as it happened and adds a merge commit. Rebase replays your commits on top of the other branch, giving a straight line but new commit IDs. Our post on how rebase keeps history cleaner goes deeper.
| Point | git merge | git rebase |
|---|---|---|
| History | Keeps the real, branched history | Rewrites into a linear history |
| Commit IDs | Existing commits unchanged | Rebased commits get new IDs |
| Extra commit | Merge commit (unless fast-forward) | None |
| Conflicts | Resolved once, in the merge | May need resolving per replayed commit |
| Safe on shared branches | Yes | No, it rewrites history others have |
| Typical use | Integrating finished work into main | Updating your own feature branch, cleaning up before a PR |
29. What does git merge --squash do?
It takes all the changes from a branch and stages them as one set in your working tree without creating a merge commit. You then make a single commit. The branch's individual commits are not part of main's history, and Git does not record the branch as merged, so git branch -d may refuse to delete it.
git switch main
git merge --squash feature/report
git commit -m "Add monthly report export"
30. What is git cherry-pick, and when should you use it?
Cherry-pick applies the changes from specific commits onto your current branch as new commits. It is useful for back-porting a fix to a release branch. Use -x to add "cherry picked from commit ..." to the message, so people can trace it. Avoid using it as a substitute for merging whole branches.
git switch release/2.3
git cherry-pick -x 4f2a9c1
git cherry-pick A..B # range: commits after A up to B
31. Which branching strategies do teams use?
GitHub Flow uses one long-lived main plus short feature branches merged through pull requests, which suits continuous deployment. Git Flow adds develop, release and hotfix branches, which suits scheduled, versioned releases but adds overhead. Trunk-based development keeps branches very short (a day or two) and relies on feature flags and strong CI.
32. What is a detached HEAD, and how do you keep work done in that state?
Detached HEAD means HEAD points directly at a commit instead of at a branch, for example after checking out a tag or a commit ID. You can commit, but those commits belong to no branch and become hard to find once you switch away. Create a branch before leaving.
git switch --detach v1.4.0
# ...experiment and commit...
git switch -c fix/from-v1.4
33. How do you find out which branches are already merged?
git branch --merged main lists branches whose tips are reachable from main, so they are safe to delete. --no-merged shows the opposite. This does not detect squash-merged branches, since their commits never entered main.
git branch --merged main
git branch -r --no-merged origin/main
34. What is git stash, and what is the difference between pop and apply?
git stash saves uncommitted changes and gives you a clean working tree. pop reapplies the latest stash and removes it from the list; apply reapplies but keeps it. By default untracked files are not stashed; add -u.
git stash push -u -m "half-done login form"
git stash list
git stash apply stash@{0}
git stash drop stash@{0}
git stash branch feature/login-form # new branch from the stash
35. What is git worktree?
A worktree is an extra working directory attached to the same repository, with a different branch checked out. You can fix a production bug in one folder while your feature work stays untouched in another, without stashing or cloning again.
git worktree add ../hotfix hotfix/payment-timeout
git worktree list
git worktree remove ../hotfix
Rebase, history rewriting and recovery
36. What does git rebase actually do?
It finds the commits on your branch that are not on the target, temporarily sets them aside, moves your branch to the target's tip and replays each commit there. The replayed commits have the same changes but new IDs. If a commit conflicts, fix it, then run git rebase --continue, or --abort to go back.
git switch feature/login
git rebase main
37. What is an interactive rebase?
git rebase -i opens a list of commits that you can edit before they are replayed. You can pick, reword, edit, squash, fixup or drop each commit, and reorder them. It is the normal way to clean up a feature branch before opening a pull request.
git rebase -i HEAD~4
38. How do fixup commits and autosquash work?
When you find a mistake in an earlier commit on your branch, commit the correction with --fixup=<commit>. Later, an interactive rebase with --autosquash moves each fixup next to its target and folds it in automatically.
git commit --fixup=3e1b2d4
git rebase -i --autosquash main
39. What does git rebase --onto do?
It moves a range of commits to a new base. The form is git rebase --onto <newbase> <upstream> <branch>: take the commits on branch that are not in upstream and replay them onto newbase. A common use is when your branch was created from another feature branch, and you want it based on main instead.
# feature/b was branched from feature/a; move only b's own commits onto main
git rebase --onto main feature/a feature/b
40. Why should you not rebase a shared branch?
Rebasing creates new commits and abandons the old ones. Anyone who already has the old commits now has a diverged history, and their next pull produces duplicates or confusing conflicts. Rebase only your own unpublished work, or branches where the team has agreed to it.
41. What are the three modes of git reset?
All three move the current branch to the given commit. --soft leaves the index and working tree alone, so the undone changes stay staged. --mixed (the default) resets the index but keeps the files, so changes are unstaged. --hard resets both index and working tree, discarding uncommitted changes.
git reset --soft HEAD~1 # undo commit, keep changes staged
git reset HEAD~1 # undo commit, keep changes unstaged
git reset --hard HEAD~1 # undo commit and throw the changes away
42. What is the difference between reset, revert and restore?
Use revert to undo something that is already pushed, reset to move your own branch back before pushing, and restore to fix individual files.
| Command | What it changes | Rewrites history? | Use it when |
|---|---|---|---|
| git revert <commit> | Adds a new commit that undoes an earlier one | No | The commit is already on a shared branch |
| git reset <commit> | Moves the branch pointer; optionally the index and files | Yes | Undoing local, unpushed commits |
| git restore <path> | Restores files in the working tree or index | No (no commits change) | Discarding edits or unstaging a file |
43. How do you revert a merge commit?
A merge commit has two parents, so you must tell Git which side to keep with -m. -m 1 keeps the mainline (the branch you merged into) and undoes what the merge brought in. If you later want to merge that branch again, you have to revert the revert first, because Git considers those commits already merged.
git revert -m 1 <merge-commit-sha>
44. What is git reflog?
The reflog is a local log of where HEAD and each branch pointed over time, including after resets, rebases and amends. It is not shared with remotes. By default, reachable entries are kept for 90 days and unreachable ones for 30 days (gc.reflogExpire and gc.reflogExpireUnreachable).
git reflog
git reflog show feature/login
45. How do you recover commits after git reset --hard?
Find the commit ID in the reflog from before the reset and move the branch back, or create a new branch at it. Uncommitted changes that were never staged or committed cannot be recovered this way.
git reflog
# a1b2c3d HEAD@{1}: commit: Add invoice PDF export
git reset --hard a1b2c3d
# or keep the current state and branch off instead:
git branch recovered a1b2c3d
46. How do you restore a deleted local branch?
Find the last commit of that branch in the reflog (look for "checkout: moving from deleted-branch") or in the output that git branch -D printed, then recreate the branch at that commit.
git reflog | grep "feature/old"
git branch feature/old 9c8d7e6
47. What is git bisect, and how do you automate it?
git bisect does a binary search through history to find the commit that introduced a bug. You mark one bad and one good commit, and Git checks out the midpoint for you to test. With git bisect run, a script decides: exit code 0 means good, 1 to 127 (except 125) means bad, and 125 means skip.
git bisect start
git bisect bad HEAD
git bisect good v1.3.0
git bisect run ./run-tests.sh
git bisect reset
48. How do you remove a file, such as a leaked secret, from all of history?
Use git filter-repo, a separate tool that the Git project itself recommends over the older git filter-branch. BFG Repo-Cleaner is another option. After rewriting, everyone must re-clone or reset, and any exposed secret must still be rotated, since forks and old clones keep copies.
git filter-repo --invert-paths --path config/secrets.env
49. How does git clean work?
git clean deletes untracked files. By default Git requires -f to actually delete. Always run -n (dry run) first. -d includes directories, -x also removes ignored files such as build output.
git clean -nd
git clean -fd
50. How do you unstage a file, or discard changes in it?
git restore --staged removes a file from the index but keeps your edits. git restore without options throws away unstaged edits by copying the file back from the index. --source lets you bring back a version from any commit.
git restore --staged app.py
git restore app.py
git restore --source=HEAD~3 app.py
51. What happens if you amend or rebase commits that you already pushed?
Your local branch no longer matches the remote, so a normal push is rejected as non-fast-forward. You would need a force push, which replaces the remote history and affects everyone who pulled it. On your own feature branch that is acceptable; on main it is not, and branch protection usually blocks it.
52. What do git gc and git maintenance do?
git gc packs loose objects, removes unreachable objects past their expiry and compresses the repository. git maintenance runs similar tasks (prefetch, commit-graph, loose objects, incremental repack) on a schedule, which keeps large repositories fast.
git gc
git maintenance start
Remotes and collaboration
53. What is a remote, and what is the difference between origin and upstream?
A remote is a named URL of another copy of the repository. origin is the name git clone gives by default. upstream is a convention for the original project when you work on a fork. "Upstream branch" also means the remote branch your local branch tracks.
git remote -v
git remote add upstream https://github.com/original/project.git
54. What is the difference between git fetch and git pull?
git fetch downloads new commits and updates remote-tracking branches like origin/main, without touching your work. git pull is a fetch followed by a merge (or a rebase, if configured) into your current branch.
| Point | git fetch | git pull |
|---|---|---|
| Downloads new commits | Yes | Yes |
| Changes your current branch | No | Yes, merges or rebases |
| Can cause conflicts | No | Yes |
| Good for | Reviewing incoming changes first | Quickly updating when you trust the incoming changes |
git fetch origin
git log --oneline main..origin/main # what is new on the remote
git pull --rebase # or set: git config --global pull.rebase true
55. What does git push -u do?
-u (--set-upstream) pushes the branch and records the remote branch as its upstream. After that, plain git push and git pull know where to go, and git status tells you how many commits you are ahead or behind.
git push -u origin feature/login
56. What is the difference between --force and --force-with-lease?
--force overwrites the remote branch no matter what is there. --force-with-lease overwrites only if the remote branch still points where your last fetch saw it, so you do not wipe out a teammate's new commits. Adding --force-if-includes also checks that you have actually integrated the remote changes you fetched.
git push --force-with-lease --force-if-includes origin feature/login
57. What is the difference between a fork and a clone?
A clone is a Git operation: a full copy of a repository on your machine. A fork is a GitHub (or GitLab) feature: a server-side copy under your account, linked to the original so you can open pull requests back to it. Forks are common in open source, where contributors do not have write access.
58. How do you keep a fork up to date?
Add the original as an upstream remote, fetch it, and merge or rebase its main into yours, then push to your fork. GitHub also has a "Sync fork" button on the fork's page.
git fetch upstream
git switch main
git merge --ff-only upstream/main
git push origin main
59. How do you authenticate to GitHub from the command line?
Use SSH keys or HTTPS with a token. GitHub stopped accepting account passwords for Git operations in 2021, so HTTPS needs a personal access token (fine-grained tokens are preferred) or a credential manager such as Git Credential Manager or the GitHub CLI.
ssh-keygen -t ed25519 -C "[email protected]"
ssh -T [email protected]
gh auth login
60. What are shallow clones, partial clones and sparse checkout?
A shallow clone (--depth) fetches only recent history, which suits CI jobs. A partial clone (--filter=blob:none) fetches all commits but downloads file contents only when needed. Sparse checkout limits which directories appear in your working tree, which helps in monorepos.
git clone --depth 1 https://github.com/org/app.git
git clone --filter=blob:none https://github.com/org/monorepo.git
git sparse-checkout set services/payments
61. Submodules or subtree: which would you choose?
A submodule stores a pointer to a specific commit of another repository. It keeps projects separate but every user must run extra commands, and it is easy to forget updates. git subtree copies the other project's files into a folder of your repository, so clones need nothing special, but syncing changes back is more work. Note that git subtree ships in Git's contrib area and may not be installed everywhere.
git submodule add https://github.com/org/shared-lib.git libs/shared
git clone --recurse-submodules https://github.com/org/app.git
git submodule update --init --recursive
62. What are Git hooks, and what are their limits?
Hooks are scripts Git runs at certain points, such as pre-commit, commit-msg and pre-push. They live in .git/hooks, which is not committed, so they are not shared automatically. You can point Git at a committed folder with core.hooksPath, or use a framework such as pre-commit. Client-side hooks can be skipped with --no-verify, so enforce the important rules again in CI.
git config core.hooksPath .githooks
63. How do you sign commits, and why?
A signature proves a commit came from the holder of a particular key. Git supports GPG, SSH and X.509 signing. GitHub shows a "Verified" badge when the key is registered on the account, and branch protection can require signed commits.
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true
git log --show-signature -1
64. How do you delete a remote branch and clean up stale references?
Delete it with git push origin --delete. Other clones still show origin/<branch> until they prune remote-tracking branches that no longer exist on the remote.
git push origin --delete feature/old
git fetch --prune
65. What is a bare repository?
A bare repository has only the Git data and no working tree. Servers and hosting platforms use bare repositories because nobody edits files there directly, and pushing to a branch that is checked out in a non-bare repository is refused by default.
git init --bare /srv/git/app.git
GitHub: pull requests, governance, Actions and security
66. What is a pull request, and what is a draft pull request?
A pull request asks to merge one branch into another and gives the team a place to review the diff, comment, run checks and approve. A draft pull request cannot be merged and does not request reviews from code owners until you mark it ready, which is useful for early feedback.
67. What merge options does GitHub offer for pull requests?
Three: "Create a merge commit" keeps all commits plus a merge commit; "Squash and merge" combines the PR into one commit on the base branch; "Rebase and merge" replays each commit onto the base without a merge commit. Admins can turn each option on or off in the repository settings.
68. How do you link a pull request to an issue so it closes automatically?
Use a closing keyword such as Closes #123, Fixes #123 or Resolves #123 in the PR description. The issue closes when the PR is merged into the repository's default branch.
69. What can branch protection rules enforce?
Branch protection can require pull request reviews (with a minimum number of approvals), reviews from code owners, passing status checks, branches to be up to date, conversation resolution, signed commits and linear history. It can also block force pushes and deletions. Read more in how branch protection rules safeguard production.
70. What are repository rulesets, and how are they different from branch protection rules?
Rulesets are the newer way to control branches and tags. Several rulesets can apply to the same branch at once and their rules combine, with the strictest setting winning, while only one branch protection rule applies to a branch. Rulesets have an enforcement status you can switch to disabled without deleting them, a bypass list for specific roles, teams or apps, and they can target tags. Organisations can also define rulesets across many repositories, depending on the plan.
71. What is a CODEOWNERS file?
CODEOWNERS maps file patterns to people or teams. GitHub automatically requests their review when a PR touches those files. The file can live in .github/, the root or docs/, and the last matching pattern wins. With "Require review from Code Owners" turned on, one approval from a listed owner is needed. Owners must have write access to the repository.
# .github/CODEOWNERS
* @org/platform-team
/terraform/ @org/infra-team
/docs/ @org/tech-writers
*.sql @org/dba-team
72. What are required status checks and the merge queue?
Required status checks are CI jobs that must pass before a PR can be merged. A merge queue groups ready PRs, tests each one against the latest base plus the PRs ahead of it, and merges them in order, so a busy main branch does not break from two PRs that each passed alone. If you use a merge queue with Actions, the workflow must also trigger on the merge_group event.
73. What is GitHub Actions, and what are its main parts?
GitHub Actions is GitHub's built-in CI/CD service. A workflow is a YAML file in .github/workflows/. Events (push, pull_request, schedule, workflow_dispatch) trigger it, it contains jobs that run on runners, and each job has steps that run commands or reusable actions.
# .github/workflows/ci.yml
name: CI
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- run: npm ci
- run: npm test
74. What is the difference between GitHub-hosted and self-hosted runners?
GitHub-hosted runners are virtual machines GitHub manages; each job gets a fresh one, and you pay by the minute on private repositories beyond your included quota. Self-hosted runners are your own machines, useful for private network access, special hardware or custom images, but you maintain and secure them. GitHub advises against self-hosted runners on public repositories, because anyone who can open a pull request could run code on them.
75. How do you handle secrets in GitHub Actions?
Store them as repository, environment or organisation secrets and reference them with ${{ secrets.NAME }}. Secrets are masked in logs but can still leak if a script transforms and prints them. Environment secrets can be protected with required reviewers before a deployment job can read them. Secrets are not passed to workflows triggered from forks by default.
- run: ./deploy.sh
env:
API_KEY: ${{ secrets.API_KEY }}
76. What is GITHUB_TOKEN, and why set permissions on it?
GitHub creates a GITHUB_TOKEN for each workflow job so it can call the GitHub API for that repository. It expires when the job finishes. Set the permissions key to grant only what the job needs, for example contents: read, so a compromised step cannot push code or change settings.
77. How does OIDC help with cloud deployments from GitHub Actions?
With OpenID Connect, the workflow requests a short-lived identity token from GitHub and exchanges it with AWS, Azure or Google Cloud for temporary credentials. You no longer store long-lived cloud keys as secrets. The job needs id-token: write permission, and the cloud trust policy should restrict which repository, branch or environment may assume the role.
permissions:
id-token: write
contents: read
78. What is a matrix build?
A matrix runs the same job several times with different variable combinations, for example several Node.js versions on Linux and Windows. Use fail-fast and max-parallel to control behaviour, and include or exclude to adjust combinations.
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
node: [20, 22]
runs-on: ${{ matrix.os }}
79. What is the difference between a reusable workflow and a composite action?
A reusable workflow (triggered with on: workflow_call) is a whole workflow with its own jobs and runners, called from a job with uses:. A composite action bundles several steps into one step that runs inside the caller's job. Use reusable workflows for shared pipelines and composite actions for small shared step sequences. For more Actions questions, see our GitHub Actions interview questions.
jobs:
build:
uses: org/ci-templates/.github/workflows/node-build.yml@v2
secrets: inherit
80. How do you secure GitHub Actions workflows against supply chain attacks?
Pin third-party actions to a full commit SHA instead of a movable tag, keep GITHUB_TOKEN permissions minimal, use OIDC instead of stored cloud keys, and treat untrusted input (PR titles, branch names) as data, never inline it into shell scripts. Be careful with pull_request_target: it runs with the base repository's secrets, so it must never check out and run code from the pull request.
81. What does Dependabot do?
Dependabot has three parts. Alerts tell you when a dependency has a known vulnerability. Security updates open pull requests that upgrade to a fixed version. Version updates, configured in .github/dependabot.yml, open regular PRs to keep dependencies current, including the actions used in your workflows.
# .github/dependabot.yml
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
82. What are secret scanning and push protection?
Secret scanning looks for known credential formats in repository content and raises alerts. Push protection blocks a push that contains a detected secret before it reaches the repository. If someone bypasses it, they must give a reason, and the bypass is recorded. Push protection for user accounts is on by default for pushes to public repositories; at repository level an admin has to enable it. Our post on storing secrets safely in Git covers prevention.
83. What is code scanning in GitHub?
Code scanning runs static analysis, usually CodeQL, on your code and shows results as alerts and as annotations on pull requests. The default setup enables it with a few clicks for supported languages; advanced setup uses a workflow file you can customise. It can be made a required check.
84. How do you authenticate scripts and tools to the GitHub API?
For personal scripts, a fine-grained personal access token scoped to specific repositories and permissions. For automation at team or organisation level, a GitHub App is better: it has its own identity, fine-grained permissions and short-lived installation tokens. Inside Actions, use GITHUB_TOKEN where possible. GitHub offers a REST API and a GraphQL API; GraphQL lets you fetch exactly the fields you need in one request.
curl -H "Authorization: Bearer $GH_TOKEN" \
-H "Accept: application/vnd.github+json" \
https://api.github.com/repos/org/app/pulls
gh api repos/org/app/pulls
85. What are GitHub webhooks, and how do you verify them?
A webhook sends an HTTP POST to your URL when an event happens, such as a push or a new pull request, so external systems like Jenkins or chat tools can react. Set a secret when creating the webhook and verify the X-Hub-Signature-256 header (an HMAC of the payload) on your server, so you only accept genuine requests.
86. What are GitHub Releases?
A release is a GitHub object built on a Git tag. It adds release notes (which GitHub can generate from merged PRs) and downloadable assets such as binaries. Releases can be created from the web UI, the API or the CLI.
gh release create v1.4.0 --generate-notes ./dist/app.tar.gz
87. How do environments and deployment protection work in GitHub Actions?
An environment (for example staging or production) groups secrets and protection rules. A job that targets it with environment: production can be held for required reviewers, a wait timer or a restriction on which branches may deploy. This is how you add a manual approval before production.
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- run: ./deploy.sh
Scenario and troubleshooting questions
88. You committed to main by mistake instead of a feature branch. Nothing is pushed. What do you do?
Create a branch at the current commit so the work is kept, move main back to match the remote, then continue on the new branch.
git branch feature/report
git reset --hard origin/main
git switch feature/report
89. You pushed a commit with an API key. What are the steps?
Revoke and rotate the key first; once pushed, assume it is compromised. Then remove it from the code, and if needed from history with git filter-repo, coordinate a force push and ask everyone to re-clone. Finally, enable push protection and move the value to a secret store so it does not happen again.
90. A bad commit reached the shared main branch and broke production. How do you undo it?
Revert it, do not reset. git revert adds a new commit that undoes the change, so nobody else's history is rewritten, and it goes through the normal PR and CI path. On GitHub you can also use the "Revert" button on the merged pull request.
git switch main
git pull
git revert 7d3e9f2
git push
91. git push is rejected with "non-fast-forward". Why, and how do you fix it?
The remote branch has commits you do not have locally. Fetch and integrate them, then push again. Do not force push to a shared branch just to make the error go away.
git pull --rebase origin main
git push
92. You ran git reset --hard and lost two days of commits. Can you get them back?
Yes, if they were committed. Look in git reflog for the entry just before the reset, then reset back to it or create a branch there. Changes that were never committed are not recoverable through Git.
git reflog
git reset --hard HEAD@{1}
93. Your feature branch is weeks behind main and has many conflicts. How do you bring it up to date?
If the branch is only yours, rebase onto main and resolve conflicts commit by commit; first squash noisy commits with an interactive rebase so there are fewer to resolve. If others share the branch, merge main into it instead. Enable rerere if you expect to repeat this. For the future, keep branches short and update them often.
git fetch origin
git rebase -i origin/main # squash noise first, then resolve conflicts
git push --force-with-lease
94. Cloning the repository is very slow. What would you check?
Look for large binaries committed into history (git count-objects -vH and git rev-list --objects --all help find them). Move such files to Git LFS with git lfs migrate, which rewrites history. For CI, use shallow or partial clones; for developers in a monorepo, partial clone plus sparse checkout.
git count-objects -vH
git lfs migrate import --include="*.zip" --everything
95. A test started failing sometime in the last 300 commits. How do you find the cause quickly?
Use git bisect with the failing test as the script. Binary search needs only about nine steps for 300 commits, and git bisect run does them without you.
git bisect start HEAD v2.1.0
git bisect run pytest tests/test_invoice.py
git bisect reset
96. Your last few commits have the wrong author email. How do you fix them?
Set the correct email, then amend the commits with --reset-author. For several commits, run the amend for each one through an interactive rebase with --exec. This rewrites history, so do it before pushing or on your own branch only.
git config user.email "[email protected]"
git rebase -r origin/main --exec "git commit --amend --no-edit --reset-author"
97. Someone deleted a branch on GitHub that is still needed. How do you get it back?
If it was the head branch of a pull request, open the PR and click "Restore branch". Otherwise, anyone with a local clone that still has the commits can push the branch again; git reflog or origin/<branch> (before pruning) will have the last commit.
git push origin origin/feature/payments:refs/heads/feature/payments
98. Windows and Linux developers keep seeing whole-file diffs caused by line endings. How do you fix it?
Commit a .gitattributes file with * text=auto (and eol=lf for scripts that must stay LF), then renormalise the files that are already in the repository.
echo "* text=auto" >> .gitattributes
git add --renormalize .
git commit -m "Normalise line endings"
99. A pull request shows a required check as "Expected: Waiting for status to be reported" and never runs. What is wrong?
The required check name in branch protection or the ruleset does not match any job that actually reports, or the workflow did not trigger for this PR (path filters, branch filters or a renamed job). Make the job name match the required check, or adjust the triggers so the job always reports.
100. A critical fix is merged to main, but the release branch also needs it. What do you do?
Cherry-pick the fix onto the release branch with -x so the origin is recorded, run the release branch's tests, and open a PR into the release branch. If the fix depends on other commits, cherry-pick those too or write a smaller back-port.
git switch release/2.3
git cherry-pick -x 5b6c7d8
git push origin release/2.3
101. Two people pushed to the same feature branch and one of them force pushed over the other's commits. How do you recover?
The person whose commits disappeared still has them locally, or in their reflog. They fetch, rebase their missing commits onto the new remote branch and push normally. To stop it happening again, the team should use --force-with-lease, which would have refused the overwrite.
git fetch origin
git rebase origin/feature/login
git push
How to prepare for a Git interview
Practise on a real repository. Create a test repository and break it on purpose: make conflicts, reset with --hard, rebase a shared branch, then recover. Learn the 50 Git commands every developer uses, then move on to the advanced Git interview questions if you are applying for senior roles.
If you want guided practice, our DevOps training in Pune covers Git, GitHub workflows and CI/CD with hands-on labs, in the classroom at Kharadi or live online across India. Teams that use GitLab can look at our GitLab training.
Frequently asked questions
Are Git interview questions different for freshers and experienced candidates?
Yes. Freshers are usually asked about basic commands, branches, merge vs rebase and fetch vs pull. Experienced candidates get recovery scenarios, history rewriting, branching strategy, branch protection and CI/CD questions, often as "what would you do if..." problems.
Should I use git switch and git restore instead of git checkout?
For new work, yes. They were added in Git 2.23 to separate branch switching from file restoring, which makes mistakes less likely. Interviewers still expect you to understand git checkout, since many scripts and older guides use it.
What is the safest way to undo a commit that is already pushed?
Use git revert. It creates a new commit that undoes the change without rewriting shared history. Reset and force push only on branches nobody else uses.
How can I recover a commit I thought I lost?
Run git reflog, find the commit ID from before the mistake, and create a branch at it with git branch recovered <id>. Reflog entries for unreachable commits are kept for 30 days by default.
What is the difference between branch protection rules and rulesets on GitHub?
Only one branch protection rule applies to a branch, while several rulesets can apply at once and combine. Rulesets also support tags, bypass lists and a disabled status without deleting them, and they can be defined across an organisation.
Do I need to know GitHub Actions for a Git interview?
For DevOps and platform roles, usually yes. Expect questions on workflow structure, secrets, GITHUB_TOKEN permissions, OIDC, matrix builds and reusable workflows.
Is Git LFS the same as storing files in GitHub?
No. With LFS, the repository stores small pointer files and the large content is kept on a separate LFS store. Without LFS, every version of a large file stays in history and makes every clone bigger.
References
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0