Lesson 5
Writing Reusable and Self-explanatory Programs
Chapter 8: git branch
Switching branches
If you check your branchtest
directory, you should see both python.txt
and idea.txt
there.
user@MACHINE:~/branchtest$ ls
idea.txt python.txt
Now, let us switch back to the main
branch.
user@MACHINE:~/branchtest$ git checkout main
Switched to branch 'main'
user@MACHINE:~/branchtest$ git branch
killer
* main
As expected, you’re back in the main
branch.
Now, if you look at your branchtest
, you should find that your killer idea.txt
file that you created earlier has disappeared! 😱😱😱
user@MACHINE:~/branchtest$ ls
python.txt
Calm down. It’s fine. The file still exists. You are looking at the latest snapshot of the main
branch, which did not have idea.txt
. You only created it in the newer killer
branch. But just to assure yourself, switch back to the killer
branch to check!
user@MACHINE:~/branchtest$ git checkout killer
Switched to branch 'killer'
user@MACHINE:~/branchtest$ ls
idea.txt python.txt
Ok, idea.txt
is still there. 😌
Now, switch back to the main
branch.
user@MACHINE:~/branchtest$ git checkout main
Switched to branch 'main'
While you still want to experiment with your killer idea, you still need to earn a living doing pragmatic things in the main
branch. So edit python.txt
, and add something else (I’ll add a c
).
a
b
c
Add/commit the updated file to the main
branch.
user@MACHINE:~/branchtest$ git add -u
user@MACHINE:~/branchtest$ git commit -m "Added c to python.txt"
[main 76917d8] Added c to python.txt
1 file changed, 1 insertion(+)
user@MACHINE:~/branchtest$ git log --oneline
76917d8 (HEAD -> main) Added c to python.txt
6ca445c Added b to python.txt
620496e Initial commit
Interestingly, when you look at the git log, it only shows you the commit history for the main
branch. You will not see the commit for idea.txt
from earlier by default.
To view all commits, add --all
as an option to git log
. I’ve also added --graph
to show a visualisation of the branches.
user@MACHINE:~/branchtest$ git log --oneline --all --graph
* 76917d8 (HEAD -> main) Added c to python.txt
| * 9d34c0a (killer) Added a new file idea.txt
|/
* 6ca445c Added b to python.txt
* 620496e Initial commit
Hopefully the graph makes sense. It shows you both your branches.