Git Code Challenges

Updated · 22 min read
mediumGit 2.53gitchallengespracticeexercisesassessment

Every lesson in this course ends with a code challenge: a small task to do in a terminal, with a hidden solution whose output was checked by running it for real. This page collects all 105 of them, so you can practice by level, revise before an interview, or find gaps in what you know. Each link opens the lesson's Practice section, where the challenge, its starting point and its solution are.

How to Practice

  1. Choose a level with the buttons below.
  2. Do the challenge before opening the solution. Most challenges continue the lesson's own example, so run the lesson's earlier commands first, in a practice folder.
  3. Predict the output before you press Enter, then compare. Being surprised is how you find what to revise.
  4. Mark the ones you missed and come back to them a few days later.

Level 1: Beginner

ChallengeLessonTask
Add a third commitWhat Is GitContinue the session above. Add the line Built by Navika, Srihitha and Advitha. to README.md, commit it with the message Add the team names, and show the history with git log --oneline.
Connect a repository to a remoteGit vs GitHub, GitLab and BitbucketContinue the session from this lesson. The command git remote add origin <address> gives your repository the address of a remote and names it origin. Add the address https://github.com/your-username/fee-tracker.git, then list the remotes again.
Predict the next snapshotHow Git Works: Snapshots, Not DifferencesContinue the session from this lesson. Add the line Contact: office@example.com to README.md, commit it with the message Add office contact, and print the snapshot with git ls-tree HEAD.
Confirm your installationHow to Install GitOpen a new terminal and ask Git for its version. Then try the short form of the same question, git -v.
Check which email a commit getsGit Config: Setting Up GitYou are still inside git-practice, where the local email is the school address. Create a file named notes.txt, commit it with the message Add practice notes, and look at the commit with git log.
Find an option yourselfGetting Help in Gitgit rm removes a file from a project. Suppose you want to see what git rm would remove, without removing anything. Use -h to find the option that does this.
Create a repository in one stepGit Init: Creating a RepositoryYou are inside fee-tracker-copy. Move up one folder, create a repository named library-app with a single command (no mkdir), move into it, and check its status.
Stage, edit, commitWorking Tree, Staging Area and RepositoryIn the same repository, create fees.txt with the line Term 1 fee: $12,000 and stage it. Then add a second line, Term 2 fee: $12,500, and commit without staging again. Print the committed file with git show HEAD:fees.txt.
Predict the short statusGit Status and File StatesContinue in the same repository. Stage notes.txt. Then add the line Tracks school fee payments. to README.md and do not stage it. Print the short status.
Watch the branch moveInside the .git FolderContinue in the same repository. Add the line Tracks school fee payments. to README.md, stage it, and commit it with the message Describe what the app does. Then print the branch file and the history.
Predict what -u stagesGit Add: Staging ChangesContinue in the same repository. Add the line Tested by Advitha. to README.md, create a new file src/Receipt.java, and run git add -u. Print the short status.
What does -a take?Git CommitContinue in the same repository. Create a new file FeeCalculator.java, add the line Late fee: $250 to fees.txt, and commit with git commit -a -m "Add late fee". Then print the short status.
Subject or body?Writing Good Commit MessagesContinue in the same repository. Add the line Sports fee: $700 to fees.txt and commit it with this command, which has two -m options:
Rename, then editGit Remove and MoveContinue in the same repository. Rename term-fees.txt to fees-2026.txt with git mv, then add the line Term 3 fee: $13,000 to the renamed file without staging that edit. Print the short status.
What is left?Git .gitignoreContinue in the same repository. Add these three lines to .gitignore: *.tmp, !report.tmp and cache/. Then create a.tmp, report.tmp, cache/data.txt and notes/cache.txt, and print the short status.
Who touched the fees?Git Log: Viewing HistoryIn the same repository, list the commits that changed fees.txt, one line each, with the short ID, the author's name and the subject. Then list the commits that did not come from Navika and contain the word "Add" in the subject.
Compare two versionsGit ShowIn the same repository, print fees.txt as it was in Srihitha's commit (9e1fcfc), and then the names and status letters of the files changed by the newest commit, on one line of details.
Three diffsGit Diff: Comparing ChangesIn the same repository, the late fee change and the exam fee line are still unstaged. Stage fees.txt, then add the line Built by Navika. to README.md without staging it. Print the short status, then the names of the files in each of the three diffs.
Predict the hunk headerHow to Read a DiffContinue in the same repository. Commit the current change, then add a new line static final int EXAM_FEE = 800; directly after the LATE_FEE line (line 3) of Fees.java. Show the diff with one line of context.
Name itNaming Commits: HEAD, ~ and ^In the same repository, write a name that starts at receipts and reaches "Add the late fee", the commit Advitha's branch started from. Then check that it gives the same ID as HEAD~3.
Pick the commandHow to Undo Changes in GitIn the same repository, three things are wrong at once: README.md has an unwanted edit that is not staged, fees.txt has a staged change you want to keep but not commit yet, and an untracked file temp.txt should go. Fix all three with the commands from the decision table, then print the short status.
Three files, three undosGit RestoreIn the same repository, make these changes: add the line Run the app. to README.md and stage it, add Hostel fee: $9,000 to fees.txt without staging it, and create a new file todo.txt. Then run git restore --staged README.md and git restore fees.txt, and print the short status.
Two commits backGit Reset: Soft, Mixed and HardIn the same repository, you are on main with the hostel fee as the newest commit. Add the line Run the app. to README.md and commit it. Then run git reset HEAD~2 and print the one-line log and the short status.
Revert the first feeGit RevertIn the same repository, revert the commit "Add the term fees" (find its ID with git log --oneline).
Preview a full cleanGit CleanIn the same repository, create a file draft.txt, a folder tmp with a file tmp/data.txt, and a file debug.log. Then preview three cleans: git clean -n, git clean -nd and git clean -ndX.

Level 2: Branching and Collaboration

ChallengeLessonTask
Predict the listsGit BranchIn the same repository, you are on main. Create a branch fix/rounding at the current commit, then create a branch docs/readme and make one commit on it that adds Run the app. to README.md. Switch back to main and print git branch --merged and git branch --no-merged.
Will it switch?Git Switch and CheckoutIn the same repository, you are on receipts. Edit README.md again by adding Run the app., then try git switch main. Then edit fees.txt by adding Exam fee: $800, and try git switch receipts.
Where am I?HEAD and Detached HEADIn the same repository, go into detached HEAD at main~2 (the first commit), then print the branch list, the first line of git status, and the files in the folder. Then go back with git switch -.
Merge the exam feeGit MergeIn the same repository, you are on feature/exam-fee, which already contains main. Switch to main, merge feature/exam-fee, and print the one-line log of the three newest commits.
Which kind of merge?Fast-Forward vs Merge CommitIn the same repository, you are on main. Create docs/readme, commit Built by Navika. to README.md there, and switch back to main. Then merge it with plain git merge and print the one-line log of the three newest commits.
Conflict or not?Resolving Merge ConflictsIn the same repository, you are on main. Create a branch feature/fees, change the term 1 fee line to Term 1 fee: $14,000 there and commit. On main, change the hostel fee line to Hostel fee: $10,000 and commit. Then merge feature/fees into main with --no-edit.
The wrong undoUndoing a MergeIn the same repository, create feature/exam-fee with two commits that each add a line to a new file exam.txt, and fast-forward main to it. Then "undo" the merge with git reset --hard HEAD~1 instead of ORIG_HEAD, and print the one-line log of the three newest commits.
A second remoteGit RemoteIn the same project, a second empty server copy is needed for backups. Create a bare repository fee-tracker-backup.git next to the others, add it as a remote named backup, push main to it (without -u), and list the remotes with their URLs.
Get Navika's release branchGit CloneIn Advitha's first clone (advitha/fee-tracker), there is no local release/1.0 yet. Run git switch release/1.0, then print the local branches.
Behind or not?Git FetchAdvitha pushes one more commit to main, adding Hostel fee: $9,000. On Navika's computer, print git status before and after git fetch, and the short log of main..origin/main.
Rebase by defaultGit PullIn Navika's clone, set pull.rebase to true for this repository. Then Advitha pushes one more commit, Navika commits one locally, and Navika runs a plain git pull.
Push twiceGit PushIn Navika's clone, add Exam fee: $800 to fees.txt, commit, and run git push two times in a row. Then print the first two lines of git status.
Is it still there?Pushing and Pulling BranchesAdvitha's computer still has origin/feature/receipts, which Navika deleted on the server. In Advitha's clone, list the remote-tracking branches before and after git fetch --prune, and ask the server for its branches.
Read the countsUpstream and Remote-Tracking BranchesIn Navika's clone on main, make two local commits without pushing (add Exam fee: $800 and then Sports fee: $700 to fees.txt). Print git branch -vv and the commits waiting to be pushed.
Fix your own branchForce Push SafelyIn Navika's clone, create fix/rounding, commit Round to the nearest dollar in a file rounding.txt with the message "Round fees", and push it with -u. Nobody else uses this branch. Then amend the message to "Round fees to the nearest dollar" and push with --force-with-lease --force-if-includes.
Sync againWorking with Several RemotesAdvitha adds the hostel fee to the official project. In Navika's clone, sync her fork: fetch upstream, fast-forward main, and push to origin. Then show git branch -vv.
Second projectGetting Started on GitHub, GitLab and BitbucketCreate a second stand-in platform repository, github-fee-receipts.git, and a new project fee-receipts next to fee-tracker, with a README.md containing # Fee Receipts. Connect it, push it with -u, and ask the "platform" which branches it has.
Does the signature still match?What Is SSHIn the same ssh-demo folder, put the original message back, Pay $12,000 to the school, and verify the old signature again, hiding the fingerprint as before.
A GitLab work accountAdding an SSH KeyAdd a second entry to ~/.ssh/config for a work account on GitLab: host name gitlab-work, real host gitlab.com, user git, and the same work key. Then ask SSH which host, user and key it would use for gitlab-work.
Work on the website's branchEditing Code OnlineIn Navika's clone, switch to the branch docs/install that was created on the website, and print the last line of README.md and the first two lines of git status.
A merge-commit mergePull Requests and Merge RequestsThis time the team merges with a merge commit. Navika pushes feature/hostel-fee as a normal branch, the platform clone merges it with --no-ff and pushes main, and Navika pulls main and deletes her branch with -d.
A second contributionForking a RepositoryAdvitha has meanwhile added the hostel fee to the original. Navika wants to contribute the exam fee. Sync main from upstream first, then create feature/exam-fee, commit Exam fee: $800, and print the one-line log of the last three commits.
A second pagePublishing a Website with PagesAdd a page docs/fees.html with the heading <h1>Fees</h1>, and a link to it in docs/index.html just before </body>: <a href="fees.html">See the fees</a>. (In your editor, add the one line. The solution writes the whole page again.) Commit, push, and list the files Git tracks.
The whole flow from the terminalThe GitHub CLIOn a practice repository of your own on GitHub, do the full life of a pull request without opening the browser:
What stays behind?Git StashOn feature/hostel-fee, edit README.md by adding Run the app., create a new file todo.txt, and run plain git stash push -m "Readme and todo". Print the short status and the stash list.
Release the hotfixGit TagOn hotfix/1.0.1, fix a typo by adding Fees are per term. to fees.txt, commit it, tag it v1.0.1 with an annotated tag, and push the branch with --follow-tags. Then ask the server for its tags.
Name the next buildReleases and Semantic VersioningAfter v1.1.0, Navika fixes a rounding bug in one commit (add Totals are rounded to the nearest dollar. to fees.txt). What should the next version be? Commit the fix, print git describe, then tag the right version and print git describe again.

Level 3: Intermediate

ChallengeLessonTask
Catch up againGit RebaseOn main, add Exam fee: $800 to fees.txt and commit. Then rebase feature/receipts onto main again, and print its last three commits.
Count the commitsMerge vs RebaseIn the same repository, compare the two branches: how many commits does each have in total? Print the count for feature-merge and for feature-rebase with git rev-list --count.
Move the hostel workRebase Onto and Stacked BranchesThe hostel feature is now ready, but it should go on top of the updated main, including the README commit. Rebase feature/hostel onto main, and print its log.
Amend twice, undo onceGit AmendAdd Hostel fee: $9,000 to fees.txt and commit it as "Add hostel". Then amend the message to "Add the hostel fee". Then amend again, this time also adding the line Exam fee: $800. Finally, undo only the last amend, and print the last commit's message and the short status.
One commit for the READMEInteractive RebaseThe branch now has four commits. Fold "Describe receipts in the README" into "Add receipt numbers" with fixup, by moving its line up under the first one. Then print the branch's commits and the files changed by the first one.
One more roundFixup Commits and AutosquashAdvitha asks for one last change: receipt numbers should start at 2001. Make it a fixup for "Add receipt numbers", autosquash without -i, and print the branch's commits and receipts.txt.
Is it still there?Removing Files from HistoryNavika also once committed a file api-key.txt and deleted it in a later commit. List every path that has ever existed in the repository's history, and check whether secrets.txt is among them.
Backport the README lineGit Cherry-PickOn release/1.0, cherry-pick "Describe receipts" from main with -x. Then print the README and count how many commits on release/1.0 contain "cherry picked from" in their message.
Predict the treesGit Reset in DepthRebuild the starting state (HEAD at "Version 2" with v2, v3 staged, v4 in the folder). The solution finds "Version 2" by its message with ":/Version 2". Then run git reset --soft HEAD~1 followed by git reset --mixed, with no commit for the second command. Print the three trees.
Three commits, wrong placeFixing Commits in the Wrong PlaceOn main, make three commits for a discount feature (create discount.txt with Sibling discount: 10%, then add Staff discount: 20%, then add Discounts apply per term). Then move all three to a new branch feature/discount, leaving main as it was.
Find the old messageGit ReflogOn main, the hostel fee commit was amended at the start of the lesson. Use main's reflog to find the commit before the amend, and print its message, without changing any branch.
Two branches goneGit Recovery: Getting Lost Work BackNavika deletes both feature/discount and a new branch feature/sports, whose commit was never checked out, so HEAD's reflog doesn't know it. Here, git commit-tree creates such a commit without touching any checked-out branch. Find both lost branch tips.
Who chose 12500?Git BlameUsing blame on FeeCalculator.java, find which commit set the term fee to 12500, and print its author and message. Use the ignore-revs setting from above.
When did the exam fee appear?Git BisectAdd an exam fee line in a new commit on top, then make three more note commits. Use git bisect run with the old and new terms --term-old=without --term-new=with to find the commit that added "Exam fee". Your test must exit with 0 when the line is missing.
When did the late fee become 300?Searching History: Grep, -S and -LUse the pickaxe to find the commit that introduced ? 300, and git grep to check whether v1.0.0 had a late fee at all.
Count the mergesGit Workflows: GitHub Flow, Gitflow and Trunk-BasedIn the three example repositories, count the merge commits on main with git rev-list --count --merges main.
Audit this repositoryGit Best PracticesIn the same repository, find three things that break the checklist: commits whose message is a single word, tracked files that look generated, and whether .gitignore covers IDE folders such as .idea/.
Is this pull request small enough?Code Review and Pull Request EtiquetteMeasure the size of feature/late-fee compared with main: the number of files and changed lines, with git diff --shortstat, and the number of commits.

Level 4: Advanced

ChallengeLessonTask
The same content twiceGit Internals OverviewCreate a folder docs with a file copy.txt containing exactly Term 1 fee: $12,000, commit it, and count the objects again. How many new objects does the commit create?
Follow the chain by handGit Objects: Blob, Tree, Commit and TagStarting from the v1.0.0 tag, reach the content of src/FeeCalculator.java using only git cat-file -p and the IDs it prints: tag, then commit, then tree, then the src tree, then the blob. The solution does each step with rev-parse, so you can compare.
Undo the skipThe Index and Refssettings.properties is still marked skip-worktree with local changes. Turn the flag off, and show what git status -s and git ls-files -v print now.
Loose againPackfiles and Garbage CollectionAfter the git gc above, Navika corrects one more fee and commits. How many loose objects and packed objects are there now?
A branch made by handBuild a Commit by HandCreate a branch feature/hostel with a commit that adds Hostel fee: $9,000 to fees.txt, using only plumbing, on top of main. Don't switch branches. Then show the graph of both branches.
A second work folderUseful Git SettingsNavika also works for a tutoring center, whose repositories are under ~/tutoring/, with the email navika@tutoring.example.com. Add a second conditional include, then print the email used in ~/tutoring/timetable, in ~/work/school-portal and in personal-site.
An undo aliasGit AliasesCreate an alias undo for reset --soft HEAD~1. Use it once, then print the short status and the one-line log.
A script with the wrong endingsGit .gitattributes and Line EndingsAdd a rule that shell scripts always use LF, create build.sh with CRLF line endings (printf "echo build\r\n"), stage it, and print its --eol information.
Compare staged changesDiff and Merge ToolsCommit the merge, then add Exam fee: $800 to fees.txt and stage it. Run the count diff tool on the staged changes only.
A hook that adds the issue numberGit HooksThe team's branches are named like fix/142-rounding. Write a prepare-commit-msg hook that adds Refs #142 (the number from the branch name) as the last line of every commit message, then commit on such a branch and print the full message.
Share a pre-commit hookSharing Hooks with a TeamIn Advitha's clone, add a shared pre-commit hook in .githooks/ that rejects files containing DEBUG, commit it with a proper message, and then try to commit a file containing DEBUG.
Name the buildGit and CI/CDIn ci-checkout, which now has the full history and tags, print the version name a pipeline would use, with git describe --tags --always --dirty. Then change fees.txt without committing and print it again.
A clone of the last two termsShallow and Partial ClonesMake a shallow clone of fee-tracker.git called recent with only the last two commits, and print its log and the contents of .git/shallow.
Only the web pagesGit Sparse CheckoutIn Navika's fee-tracker folder, keep only web/pages, then list the top-level entries and print the sparse-checkout list.
The largest versionGit Large File Storage (LFS)Print only the single largest blob in Navika's history, with its size and path.
Pack again after more workKeeping Repositories FastMake three more commits in Navika's repository, check how many loose objects there are, then run git gc --quiet and check again.
A quick look at an old commitGit WorktreeFrom Navika's folder, add a detached worktree at ../fee-tracker-old for main, print its fees.txt and the worktree list, then remove it.
A third cloneGit SubmodulesClone the Fee Tracker as srihitha in one step, with its submodule, and print the submodule's status and the last line of rules/rules.txt.
What came from whereGit SubtreePrint the git-subtree-split line of every squash commit in the Fee Tracker's history, newest first.
A signed release tagSigning Commits and TagsCreate a signed tag v1.1 on the latest commit with the message "Fee Tracker 1.1", then print the subject and %G? letter of the last three commits.
Stop tracking a settings fileKeeping Secrets Out of GitNavika's config/local.properties was committed before it was ignored. Make Git stop tracking it, without deleting her copy, and ignore it from now on.
One patch for a branchGit Patches: Sharing Commits as FilesIn Navika's repository, create a branch fix/exam-fee from main, commit a change to the exam fee, and write the branch's commits as patches into ../outgoing. Then show the subject line of the patch.
A one-branch bundleGit Bundle and ArchiveIn Navika's fee-tracker, create a bundle with only the branch feature/hostel-fee, list its heads, clone it into a folder review with that branch checked out, and print the clone's current branch and log.
Theirs for one mergeMerge StrategiesAdvitha's branch is right about every conflict. Create a branch advitha/late from the commit before Navika's "Raise the late fee in code", change the late fee in Fees.java to 275 (with two spaces), and merge it into main so that her side wins the conflict. Print the late line.
A second trialGit RerereWith rerere on and autoUpdate off, run git merge feature/fees in Navika's repository again. The resolution was forgotten, so resolve the conflict with $300 and a note, commit, and print the Late fee line.
A clean trial mergeHow Git MergesCreate a branch advitha/books from "Add the fee list" that adds a file books.txt, then test-merge it into main with git merge-tree --write-tree and print the exit code. Finally, confirm that main still has no books.txt.

Level 5: Professional Skills

ChallengeLessonTask
IntelliJ as the merge toolGit in VS Code and IntelliJ IDEAConfigure Git to use IntelliJ IDEA for merges, with the tool name intellij, and print the two settings you created.
The graph a client would drawGit GUI ClientsIn Navika's repository, merge feature/late-fee into main with a merge commit, then print the graph a GUI client would show.
The Gradle wrapperGit for Java ProjectsAdd a gradlew script, make it executable in Git, and give it LF line endings in .gitattributes, then print its mode and its eol attribute.
A patch releaseVersioning Java Builds from Git TagsFix a typo in a new commit after v1.1.0, print the description, tag it as v1.1.1, and print the description again.
Rejected againCommon Git Errors: Push and PullAdvitha pushes a new sports fee. Without pulling, Navika commits a change to fees.txt. Fix the rejected push and print the last three commits.
Bring the branch backCommon Git Errors: Branches and MergesNavika deleted the original feature/late-fee with -D earlier, and then created a new branch with the same name. Find the old tip in the reflog (the commit "Raise the term fee more"), move the branch back to it, and print its log.
A lost identityCommon Git Errors: Setup and AccessUnset user.email globally, try to commit a change, and then fix it with a repository-only email address.
Modernize these commandsModern Git CommandsRewrite git checkout -b feature/exam-fee, git checkout -- fees.txt and git reset HEAD fees.txt with modern commands, and run them on a change to fees.txt.
A Git 3.0-style repositoryGit 3.0: What Is PlannedCreate a repository named future with both planned defaults, using settings instead of options, and print its object format, ref format and branch name.

Was this tutorial helpful?