Git Exercises With Solutions: Intermediate
13 intermediate Git exercises with starting repositories, expected results, hints and explained solutions: pushing with upstreams, rejected pushes, reverting, resetting, recovering with the reflog, stashing, cleaning, ranges, blame, bisect, aliases and hooks.
kvi5hnuCode Sprout team member9 min readOn this page
The second of three exercise sets covers Parts 4 to 7: remotes, undoing and recovering, investigating history, and configuration. It works the same way as the beginner set: each runnable block builds a starting repository, you add your commands under # --- your commands here ---, and the # --- check --- section prints the state to compare with the expected result.
Several exercises use a bare repository, server.git, in the same folder as a stand-in for a hosting service, so you can push, fetch and pull without a network. As before, give messages on the command line, because the sandbox has no editor.
1. Push a new branch and track it
You've committed a new page on the branch ridge-page. Push it to origin, and set it up so that plain git push and git pull work on it from now on.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
git switch -q -c ridge-page
echo "Ridge loop" > ridge.txt; git add .; git commit -q -m "Add ridge page"
# --- your commands here ---
# --- check ---
echo "upstream: $(git rev-parse --abbrev-ref ridge-page@{upstream} 2>/dev/null || echo none)"
git -C ../server.git log --format=%s ridge-page 2>/dev/null || echo "not on the server"
upstream: none
not on the server
Expected result after solving it:
upstream: origin/ridge-page
Add ridge page
Add lake page
Hint
git push needs to be told the remote and branch the first time, and an option records them as the upstream.
Answer
git push -u origin ridge-page
-u (--set-upstream) pushes the branch and records origin/ridge-page as its upstream, so later git push and git pull need no arguments, and git status reports ahead and behind counts. git config --global push.autoSetupRemote true makes plain git push do this automatically for new branches (article 20).
2. A rejected push
A teammate pushed while you were working, so your push of Add ridge page is rejected. Get your commit onto the server after your teammate's, with a straight-line history and no merge commit.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
cd ..; git clone -q server.git ana; cd ana
echo "Forest loop" > forest.txt; git add .; git commit -q -m "Add forest page"; git push -q
cd ../trail-guide
echo "Ridge loop" > ridge.txt; git add .; git commit -q -m "Add ridge page"
git push -q 2>/dev/null || echo "(push rejected)"
# --- your commands here ---
# --- check ---
git -C ../server.git log --format=%s --graph main
(push rejected)
* Add forest page
* Add lake page
Expected result after solving it:
(push rejected)
* Add ridge page
* Add forest page
* Add lake page
Hint
Fetch the new commit and replay yours on top of it, then push.
Answer
git pull --rebase
git push
git pull --rebase fetches Add forest page and replays your commit after it, so the push is a fast-forward for the server. A plain git pull would also work, but adds a merge commit. Never --force here, because that would delete your teammate's commit from the server (articles 19 and 20).
3. Undo a pushed commit
The commit Change lake distance was pushed, and it was wrong. Undo its change on main in a way that's safe for everyone who already pulled it, and push the result.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
echo "Ridge loop" > ridge.txt; git add .; git commit -q -m "Add ridge page"
echo "Lake loop: 50 km" > lake.txt; git commit -q -am "Change lake distance"
echo "Forest loop" > forest.txt; git add .; git commit -q -m "Add forest page"
git push -q
# --- your commands here ---
# --- check ---
cat lake.txt
git -C ../server.git log --format=%s main
Lake loop: 50 km
Add forest page
Change lake distance
Add ridge page
Add lake page
Expected result after solving it:
Lake loop
Revert "Change lake distance"
Add forest page
Change lake distance
Add ridge page
Add lake page
Hint
Rewriting pushed history isn't safe. Add a new commit that does the opposite.
Answer
git revert --no-edit HEAD~1
git push
git revert creates a new commit that reverses the old one's changes, so nobody's history is rewritten. The commit to revert is HEAD~1, or use its ID from git log --oneline. git reset would remove the commit locally, but then pushing needs --force, which breaks teammates' clones (article 24).
4. Uncommit, keeping the work
Your last two commits aren't pushed, and you want to redo them differently. Remove both commits from main, but keep all their changes in the working tree, unstaged.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
echo "Ridge loop" > ridge.txt; git add .; git commit -q -m "WIP ridge"
echo "Lake loop: 5.4 km" > lake.txt; git commit -q -am "WIP lake"
# --- your commands here ---
# --- check ---
git log --format=%s
git status --short
WIP lake
WIP ridge
Add lake page
Expected result after solving it:
Add lake page
M lake.txt
?? ridge.txt
Hint
git reset has three modes. The default one moves the branch and unstages, without touching files.
Answer
git reset HEAD~2
git reset HEAD~2 (the default --mixed mode) moves main back two commits and resets the index, but leaves the files as they are, so the changes show as unstaged ( M) and untracked (??). --soft would have kept them staged, and --hard would have discarded them (article 24).
5. Recover from reset --hard
Someone ran git reset --hard HEAD~2 on main by mistake, removing two commits that were never pushed. Bring main back to where it was before the reset.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
echo "Ridge loop" > ridge.txt; git add .; git commit -q -m "Add ridge page"
echo "Forest loop" > forest.txt; git add .; git commit -q -m "Add forest page"
git reset -q --hard HEAD~2
# --- your commands here ---
# --- check ---
git log --format=%s
Add lake page
Expected result after solving it:
Add forest page
Add ridge page
Add lake page
Hint
The reflog records every position HEAD has had. git reflog lists them.
Answer
git reset --hard HEAD@{1}
HEAD@{1} is where HEAD was one move ago: just before the reset. Resetting back to it restores both commits. ORIG_HEAD, which reset sets, works too: git reset --hard ORIG_HEAD. Check git reflog first in real situations, since other commands may have moved HEAD in between (article 26).
6. Recover a deleted branch
The branch cave-page was deleted with git branch -D before it was merged or pushed. Recreate it, pointing to its last commit.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
git switch -q -c cave-page
echo "Cave loop" > cave.txt; git add .; git commit -q -m "Add cave page"
echo "Cave loop: 3 km" > cave.txt; git commit -q -am "Add cave distance"
git switch -q main
git branch -q -D cave-page
# --- your commands here ---
# --- check ---
git log --format=%s cave-page 2>/dev/null || echo "no cave-page branch"
no cave-page branch
Expected result after solving it:
Add cave distance
Add cave page
Add lake page
Hint
Before switching to main, HEAD was at the branch's last commit. Look at git reflog.
Answer
git branch cave-page HEAD@{1}
The reflog line checkout: moving from cave-page to main shows that HEAD@{1} was the tip of cave-page, so git branch cave-page HEAD@{1} recreates it. The deletion message (Deleted branch cave-page (was <id>)) also prints the ID. Commits stay recoverable until the reflog entries expire (article 26).
7. Stash for an urgent fix
You're halfway through editing lake.txt when an urgent typo fix is needed in ridge.txt. Without committing your lake work, commit the fix Ridge loop: 8 km to ridge.txt as Fix ridge typo, then get your lake work back, still uncommitted.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
echo "Rigde loop: 8 km" > ridge.txt; git add .; git commit -q -m "Add ridge page"
echo "Lake loop: 5.4 km, half done" > lake.txt
# --- your commands here ---
# --- check ---
git log --format=%s
git status --short
cat lake.txt ridge.txt
echo "stashes: $(git stash list | wc -l)"
Add ridge page
Add lake page
M lake.txt
Lake loop: 5.4 km, half done
Rigde loop: 8 km
stashes: 0
Expected result after solving it:
Fix ridge typo
Add ridge page
Add lake page
M lake.txt
Lake loop: 5.4 km, half done
Ridge loop: 8 km
stashes: 0
Hint
git stash puts uncommitted changes aside and leaves a clean working tree. git stash pop brings them back.
Answer
git stash
echo "Ridge loop: 8 km" > ridge.txt
git commit -am "Fix ridge typo"
git stash pop
Stashing makes sure the fix commit contains only the fix. git stash pop reapplies the lake changes and removes the stash, so the list is empty again. Here you could also have staged only ridge.txt, but stashing is the general solution, for example when you need to switch branches for the fix (article 27).
8. Clean the working tree
Delete all untracked files and folders, but keep ignored files, such as .env, which holds local settings. Tracked files and changes must not be touched.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
echo ".env" > .gitignore; git add .; git commit -q -m "Ignore env"
echo "SECRET=local" > .env
mkdir tmp; echo "x" > tmp/scratch.txt; echo "y" > notes.txt
echo "Lake loop: 5.4 km" > lake.txt
# --- your commands here ---
# --- check ---
ls -A | grep -v '^.git$'
git status --short
.env
.gitignore
lake.txt
notes.txt
tmp
M lake.txt
?? notes.txt
?? tmp/
Expected result after solving it:
.env
.gitignore
lake.txt
M lake.txt
Hint
git clean needs -f to delete anything, and an extra option for folders. Try -n first to preview.
Answer
git clean -fd
git clean -fd deletes untracked files and folders, leaving ignored files alone. Adding -x would delete ignored files too, including .env. git clean -nd previews the same deletion, which is worth doing first, because cleaned files can't be recovered from Git (article 28).
9. Which commits haven't been merged?
Write the subjects of the commits that are on topic but not on main, one per line, oldest first, into answer.txt.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
git switch -q -c topic
echo "Cave loop" > cave.txt; git add .; git commit -q -m "Add cave page"
echo "Cave loop: 3 km" > cave.txt; git commit -q -am "Add cave distance"
git switch -q main
echo "Ridge loop" > ridge.txt; git add .; git commit -q -m "Add ridge page"
git switch -q topic
echo "Cave parking" >> cave.txt; git commit -q -am "Describe cave parking"
# --- your commands here ---
# --- check ---
cat answer.txt 2>/dev/null || echo "no answer.txt yet"
no answer.txt yet
Expected result after solving it:
Add cave page
Add cave distance
Describe cave parking
Hint
The two-dot range A..B means "commits reachable from B but not from A".
Answer
git log --reverse --format=%s main..topic > answer.txt
main..topic selects the three commits on topic that main doesn't have, and --reverse lists them oldest first. git log main...topic (three dots) would also include Add ridge page, the commit on main that topic lacks (article 29).
10. Who changed this line?
Find out who last changed line 2 of trails.txt, and write just their name into answer.txt.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
printf 'Lake loop: 5 km\nRidge loop: 8 km\nForest loop: 6 km\n' > trails.txt
git add .; git commit -q -m "Add trails list"
sed -i 's/Ridge loop: 8 km/Ridge loop: 8.5 km/' trails.txt
git -c user.name="Ana Diaz" -c user.email=ana@example.com commit -q -am "Correct ridge distance"
sed -i 's/Forest loop: 6 km/Forest loop: 6.5 km/' trails.txt
git -c user.name="Lee Park" -c user.email=lee@example.com commit -q -am "Correct forest distance"
# --- your commands here ---
# --- check ---
cat answer.txt 2>/dev/null || echo "no answer.txt yet"
no answer.txt yet
Expected result after solving it:
Ana Diaz
Hint
git blame -L <start>,<end> limits the output to some lines. --porcelain prints the author on a line of its own.
Answer
git blame -L 2,2 --porcelain trails.txt | sed -n 's/^author //p' > answer.txt
git blame -L 2,2 shows the commit and author for line 2. --porcelain gives machine-readable output with an author <name> line, which sed extracts. Reading git blame -L 2,2 trails.txt and typing the name works too (article 30).
11. Find the commit that broke the build
check.sh passes at the first commit and fails at the latest. Use git bisect to find the first commit where it fails, and write that commit's subject into answer.txt. Finish with the repository back on main, with the bisect session ended.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
printf '#!/bin/sh\ngrep -q "km" lake.txt\n' > check.sh; chmod +x check.sh
echo "Lake loop: 5 km" > lake.txt; git add .; git commit -q -m "Add check script"
for page in ridge forest cave river meadow; do echo "$page" > $page.txt; git add .; git commit -q -m "Add $page page"; done
git tag -a good-start -m "known good" HEAD~5
echo "Lake loop: 5 miles" > lake.txt; git commit -q -am "Tidy lake page"
for page in canyon summit; do echo "$page" > $page.txt; git add .; git commit -q -m "Add $page page"; done
# --- your commands here ---
# --- check ---
cat answer.txt 2>/dev/null || echo "no answer.txt yet"
git status | head -1
no answer.txt yet
On branch main
Expected result after solving it:
Tidy lake page
On branch main
Hint
git bisect start <bad> <good> starts a session, and git bisect run <script> tests each step automatically: exit code 0 means good, and 1 to 127 (except 125) means bad.
Answer
git bisect start main good-start
git bisect run ./check.sh
git log -1 --format=%s refs/bisect/bad > answer.txt
git bisect reset
bisect run checks out the middle of the range, runs ./check.sh, and halves the range until it finds Tidy lake page, which changed "km" to "miles". The first bad commit stays in refs/bisect/bad until git bisect reset, which ends the session and returns to main (article 31).
12. Create an alias
Create a Git alias, so that git last prints the subject of the latest commit, and nothing else. Set it in this repository's configuration.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
echo "Ridge loop" > ridge.txt; git add .; git commit -q -m "Add ridge page"
# --- your commands here ---
# --- check ---
git last 2>/dev/null || echo "git last isn't defined"
git last isn't defined
Expected result after solving it:
Add ridge page
Hint
Aliases live in the alias section of the configuration: alias.<name> holds the command, without the leading git.
Answer
git config alias.last "log -1 --format=%s"
git config alias.last "log -1 --format=%s" stores the alias in .git/config. Add --global to make it available in every repository. Arguments typed after git last are appended to the command (article 34).
13. Reject short commit messages with a hook
Add a commit-msg hook to this repository that rejects commit messages whose first line is shorter than 10 characters, so git commit -m "wip" fails, while longer messages are accepted.
git init -q --bare server.git
git clone -q server.git trail-guide 2>/dev/null && cd trail-guide
echo "Lake loop" > lake.txt; git add .; git commit -q -m "Add lake page"; git push -q origin main
true
# --- your commands here ---
# --- check ---
git commit -q --allow-empty -m "wip" 2>/dev/null && echo "wip: accepted" || echo "wip: rejected"
git commit -q --allow-empty -m "Add cave page" 2>/dev/null && echo "long message: accepted" || echo "long message: rejected"
git log --format=%s
wip: accepted
long message: accepted
Add cave page
wip
Add lake page
Expected result after solving it:
wip: rejected
long message: accepted
Add cave page
Add lake page
Hint
The commit-msg hook receives the path of a file containing the message as its first argument. A non-zero exit code rejects the commit. Hooks must be executable.
Answer
cat > .git/hooks/commit-msg <<'EOF'
#!/bin/sh
first=$(head -n 1 "$1")
if [ ${#first} -lt 10 ]; then
echo "Commit message too short: write at least 10 characters." >&2
exit 1
fi
EOF
chmod +x .git/hooks/commit-msg
Git runs .git/hooks/commit-msg with the message file's path, and the script measures the first line and exits with 1 when it's too short, which aborts the commit. Hooks in .git/hooks aren't shared through pushes, so teams use core.hooksPath with a committed folder, configuration-based hooks, or a framework (article 36).
Common questions
Why do some exercises use HEAD@{1}, and how do I know which number to use?
HEAD@{n} is where HEAD was n moves ago. Always look at git reflog first: it lists each position with the command that moved it, so you can pick the right entry rather than guessing.
Exercise 3 reverts HEAD~1. What if the bad commit is further back?
Find it with git log --oneline and revert it by ID. Reverting works for any commit, as long as later commits don't depend on its changes. Otherwise you'll get conflicts to resolve.
Can I solve the bisect exercise by hand?
Yes: git bisect start main good-start, then run ./check.sh at each step and type git bisect good or git bisect bad depending on its result. git bisect run automates exactly that.
Summary
push -usets upstreams, andpull --rebaseintegrates before pushing again. Revert pushed mistakes, and reset unpushed ones.- The reflog recovers resets and deleted branches.
stashsets work aside, andcleanremoves untracked files. - Ranges,
blame -Landbisect runanswer "what's missing?", "who?" and "when did it break?". - Aliases and hooks customize Git per repository or globally.
Practice questions
In the rejected-push exercise, what would git push --force have done to the server's history?
Answer
It would have replaced the server's main with your local main, which doesn't contain Add forest page. Your teammate's commit would disappear from the server, and their next pull would show diverged branches. --force-with-lease would have refused, because your view of origin/main was out of date.
Why does git clean -fd keep .env in exercise 8, and which option would delete it?
Answer
.env matches a pattern in .gitignore, and git clean leaves ignored files alone by default. -x also deletes ignored files, and -X deletes only ignored files.
Ready for more? The advanced exercises cover tags, worktrees, submodules, patches, bundles, rewriting history and internals.
Previous: Git Exercises With Solutions: Beginner

More in Git Course
Quiz: Git Delicate Details
Twenty-five questions on Git's subtle corners: what commit -a and stash leave out, empty folders, ignore patterns and negation, HEAD~ versus HEAD^, ours and theirs in a rebase, tags that don't move or don't push, describe, merge reverts, diff exit codes, stash conflicts and more.
Quiz: Git Interview Questions
Thirty Git questions of the kind asked in developer interviews: Git versus GitHub, the staging area, merge versus rebase, fetch versus pull, reset, revert and restore, detached HEAD, conflicts, force pushing, stash, cherry-pick, reflog, bisect, submodules, LFS and how commits are identified.
Quiz: Git Course Final Exam (All Parts)
The final exam for the Git course: thirty questions across all twelve parts, from the three areas and staging through branching, remotes, undoing, history investigation, configuration, tags, larger projects, patches, rewriting, internals and troubleshooting.
Quiz: Professional Git Practice (Git Part 12)
Sixteen questions on migrating to Git from Subversion, TFVC and Mercurial, team best practices for commits, branches and reviews, repository hygiene, and diagnosing and fixing the most common Git errors, with explanations.
Discussion
Sign in to ask a question or share what you learned.