Git Switch is a command used in Git version control to change branches safely. This command is crucial for developers working on multiple features or versions simultaneously within a project.
Example 1: Switching to an existing branch named ‘development’
git switch development
This command switches the current working directory to the ‘development’ branch. Verify by running git branch
and checking if the active branch is ‘development’.
Example 2: Creating and switching to a new branch ‘feature-123’
git switch -c feature-123
Here, -c
creates a new branch named ‘feature-123’ and switches to it. To confirm, execute git branch
and ensure ‘feature-123’ is listed.
Example 3: Switching back to the previous branch (often ‘master’ or ‘main’)
git switch -
Using -
with git switch
reverts to the previously active branch. Check with git branch
to verify.
Example 4: Switching to a specific commit hash for inspection
git switch 1a2b3c4
This command detaches HEAD to the commit specified by ‘1a2b3c4’. Verify by running git log
and examining the HEAD position.
Example 5: Creating an orphan branch (without any history)
git switch --orphan new-branch
Using --orphan
creates a new branch ‘new-branch’ without any commit history. Check with git log
and ensure no previous commits exist.
Example 6: Switching to a branch by specifying its remote tracking branch
git switch origin/main
This command switches to the local copy of the remote branch ‘main’ from the ‘origin’ repository. Verify by using git branch -vv
to see the tracking information.
Example 7: Checking out a file from another branch
git switch --
Replace <filename>
with the actual file name to check out a specific file from another branch into the current branch. Verify by inspecting the file contents.
Example 8: Switching to a specific tag for a stable release
git switch tags/v1.0.0
By specifying the tag ‘v1.0.0’, this command switches to a specific stable release. Verify by running git describe --tags
to confirm the current tag.
Example 9: Creating an empty branch (no commits)
git switch --orphan empty-branch
Similar to Example 5, this creates a new branch ’empty-branch’ with no commit history. Verify using git log
to ensure no commits are present.
Example 10: Switching to a branch based on partial name matching
git switch feature-
This command switches to the branch whose name starts with ‘feature-‘. Verify by inspecting the active branch with git branch
.
Discussion about this post