Git
Picking a single commit
Learn to pick a single commit from another branch.
Choosing with a commit hash
Every commit has a unique hash value. The git log --oneline command lists commits with their hashes on single lines, and this is where you take the hash to give cherry-pick. git rev-parse HEAD gives the hash of the current commit directly.
git log --oneline
a1b2c3d ozellik eklendi
7f0c411 temel kayit
This is how the commit to move is picked out.
One commit from another branch
To take a single commit from another branch you first take its hash and then apply it to the current branch. If you keep the hash in a variable it does not get lost between the two commands; git checkout - returns to the previous branch.
HASH=$(git rev-parse HEAD)
git checkout -
git cherry-pick $HASH
This way only the commit you chose is moved.
Exercise Move a commit by hash
Create temel.txt, add it and save quietly. Open a branch named gelisme; there create iki.txt with iki inside, add it and save quietly. Store the hash of the HEAD commit in the HASH variable, go back to the previous branch, apply that commit with git cherry-pick, and print the contents of iki.txt.
Show example solution
git init -q
echo temel > temel.txt
git add temel.txt
git commit -q -m "temel"
git checkout -q -b gelisme
echo iki > iki.txt
git add iki.txt
git commit -q -m "iki"
HASH=$(git rev-parse HEAD)
git checkout -q -
git cherry-pick $HASH >/dev/null 2>&1
cat iki.txt
Test yourself
-
How does a commit moved by cherry-pick appear on the target branch?
- It is copied exactly with the same hash number
- It is removed from the source branch because it moved
- It appears as a new commit with the same changes
- It is stored only as a file stash
Show answer
It appears as a new commit with the same changes — cherry-pick applies the changes of the commit and creates a new commit on the target branch; the original commit stays on the source branch.
-
Take the hash
HASH=$(git rev-parse ____)
git checkout -
git cherry-pick $HASH
Show answer
HASH=$(git rev-parse HEAD)
git checkout -
git cherry-pick $HASH
-
Hash tools
- commit hash
- Unique id of a commit
- git log --oneline
- Lists hashes one per line
- git rev-parse HEAD
- Gives the current hash
- git checkout -
- Returns to the previous branch
Next lesson: Conflict case