Use git branch --contains for Commit Check
In this step, we will learn how to use the git branch --contains
command to find out which branches contain a specific commit. This is useful when you have multiple branches and want to know where a particular change exists.
First, ensure you are in your project directory:
cd ~/project/my-time-machine
Let's create a new branch to demonstrate this command. We'll call it feature-branch
:
git branch feature-branch
This command creates a new branch, but it doesn't switch to it. You can see your branches using git branch
:
git branch
You should see something like this, with master
highlighted (indicating it's the current branch):
* master
feature-branch
Now, let's get the hash of our first commit. We can use git log --oneline
to see a condensed log with commit hashes:
git log --oneline
You will see output similar to this (your hashes will be different):
e4f5g6h (HEAD -> master) Update message.txt
a1b2c3d Add a second file
abcdef0 Send a message to the future
Copy the hash of the first commit ("Send a message to the future"). In the example above, it's abcdef0
.
Now, let's use git branch --contains
with the hash of the first commit:
git branch --contains abcdef0
Replace abcdef0
with the actual hash of your first commit.
The output should show both master
and feature-branch
:
* master
feature-branch
This tells us that the commit "Send a message to the future" exists on both the master
and feature-branch
branches. This makes sense because we created feature-branch
while on the master
branch, and the first commit was already part of master
.
Now, let's get the hash of the last commit ("Update message.txt"). In the example above, it's e4f5g6h
.
Use git branch --contains
with the hash of the last commit:
git branch --contains e4f5g6h
Replace e4f5g6h
with the actual hash of your last commit.
The output should only show master
:
* master
This is because the last commit was made on the master
branch after we created feature-branch
. Therefore, feature-branch
does not contain this commit.
The git branch --contains
command is a powerful tool for understanding the relationship between commits and branches, helping you track where specific changes have been integrated.