All Git Exercises

Copy one commit to another branch with cherry-pick

Description: The branch develop has an unfinished feature and a bug fix. Bring only the bug fix commit to main.

Hint:

  • Find the commit with git log, then use git cherry-pick with its name.

Solution

Terminal output

$ git log –oneline develop
0bbe41e (develop) Fix header bug
c03680a Add feature (not ready)
1e3d759 (HEAD -> main) Add home
$ git cherry-pick develop
[main 97e3b7d] Fix header bug
Date: Sat Jan 10 11:31:00 2026 +0000
1 file changed, 1 insertion(+)
create mode 100644 fix.txt
$ git log –oneline
97e3b7d (HEAD -> main) Fix header bug
1e3d759 Add home
$ ls
fix.txt
home.txt

How it works

  • The fix is the latest commit of develop, so we can use the branch name. Otherwise use the hash.
  • Only fix.txt came to main. The unfinished feature.txt did not.

Read Git Cherry Pick.

Recover a deleted branch with git reflog

Description: You deleted the branch feature-x with git branch -D and you want it back.

Hint:

  • The reflog keeps the commit. Create a branch from it.

Solution

Terminal output

$ git reflog -3
1e3d759 (HEAD -> main) HEAD@{0}: checkout: moving from feature-x to main
72e9eac HEAD@{1}: commit: Add feature work
1e3d759 (HEAD -> main) HEAD@{2}: checkout: moving from main to feature-x
$ git branch feature-x HEAD@{1}
$ git log –oneline feature-x
72e9eac (feature-x) Add feature work
1e3d759 (HEAD -> main) Add home

How it works

  • HEAD@{1} is the commit where HEAD was before we moved to main, which is the last commit of the deleted branch.
  • The reflog works only on your computer and for some time (90 days by default).

Read Git Reflog.

Delete a file with git rm

Description: Remove the file old.txt from the project and commit the change.

Hint:

  • git rm deletes the file and stages the deletion.

Solution

Terminal output

$ git rm old.txt
rm 'old.txt'
$ git status -s
D old.txt
$ git commit -m "Remove old.txt"
[main 29d3f88] Remove old.txt
1 file changed, 1 deletion(-)
delete mode 100644 old.txt
$ ls
keep.txt

How it works

  • D in the status means the deletion is staged.
  • The file is still in the history, so you can bring it back from an older commit.

Read Git rm and mv.

Rename a file with git mv

Description: Rename readme.txt to README.md and commit the change.

Hint:

  • git mv old new renames the file and stages the change.

Solution

Terminal output

$ git mv readme.txt README.md
$ git status -s
R readme.txt -> README.md
$ git commit -m "Rename readme to README.md"
[main 6b0ae04] Rename readme to README.md
1 file changed, 0 insertions(+), 0 deletions(-)
rename readme.txt => README.md (100%)
$ git log –oneline –follow — README.md
6b0ae04 (HEAD -> main) Rename readme to README.md
38fa585 Add readme

How it works

  • R in the status means renamed.
  • --follow keeps the history of the file after the rename.

Read Git rm and mv.