In the previous tutorial, the checkout
subcommand was used to switch betweeen branches, but there’s a lot more that it can do.
“Checking out” is how you switch between different points of the repository’s history.
You can checkout
branches, tags, and commits.
Tags
Tags are just named pointers to commits (with optional extra data). They’re usually used for marking versions of software, which makes it really easy to jump between versions in a git repository.
For example, to check out the latest version of Linux (at the time of writing), you can use the following command in the Linux mainline git repository directory:
|
|
This works because there is a tag named v5.10-rc6
, which points to the commit for version 5.10, release candidate 6 of Linux.
A similar command can be used to checkout version 5.8:
|
|
Branches
To switch to a branch, use git checkout
followed by the branch name.
This command will switch to the master
branch:
|
|
Or for the devel
branch:
|
|
Create and checkout a branch
The -b
flag will tell Git to create the branch, then check it out.
Here’s an example:
|
|
This will first switch to the master
branch, then create a new branch called feature-foo
which will be based off of master
.
git checkout -b
will create a branch which is based off of the currently checked-out branch.
Commits
You can also check out specific commits using their SHA-1 hash.
To find commits to check out, use the git log
command.
Here’s a commit we’re going to check out:
|
|
To check it out, you can use the following command:
|
|
Since that’s pretty tricky to type, especially without copy/paste abilities, Git allows using as few characters of the hash as possible while staying unique. Usually 6 or 8 characters is ideal. Here are two examples using the same commit as before:
|
|
Getting back
After checking out a tag or commit, Git will usually print a message that looks like the following:
|
|
Basically, it’s saying that you’re in a state called “detached HEAD” state (remember HEAD is another name for the latest commit).
To exit “detached HEAD” state and return to the normal HEAD, use the following command:
|
|
If you make changes in “detached HEAD” mode and you want to save them, use the following command to create a new branch with the changes:
|
|