Git Switch
git switch
is a command introduced in Git 2.23.0 (released 2019) to simplify the process of switching between branches and to delineate the responsibilities of git checkout
, which was somewhat overloaded with functionalities. Here is how and why you might use git switch
in your workflow:
Why Use git switch?
-
Clarity and Readability: The
git switch
command clearly indicates the action you are performing, i.e., switching between branches. This makes your intentions explicit when you use the command, improving readability and understanding for people reviewing your commands or scripts. -
Avoiding Mistakes: Using a separate command to switch branches helps avoid accidental file modifications or deletions that can sometimes occur when using the
git checkout
command improperly. -
Intuitive for New Users: For new Git users, it's more intuitive to use a command named "switch" to switch between branches rather than "checkout," which might imply checking out files rather than branches.
How to Use git switch?
Creating a New Branch and Switching to It
To create a new branch and switch to it in a single command, you can use:
git switch -c new_branch
bash
Switching Between Existing Branches
To switch to an existing branch, use:
git switch existing_branch
bash
Switching Back to the Previous Branch
To switch back to the previous branch you were on, use:
git switch -
bash
Orphan Branch
To create an orphan branch (a branch with no commit history), use:
git switch --orphan orphan_branch
bash
Example Workflow with git switch
Here's how a workflow using git switch
might look:
-
Checking Current Branch
Check your current branch using:
git branch
bash -
Creating a New Branch
Create a new branch and switch to it using:
git switch -c feature_branch
bash -
Making Changes and Committing
Make changes to your files and commit them using:
git add . git commit -m "Implemented a new feature"
bash -
Switching Back to Main Branch
Switch back to the main branch using:
git switch main
bash -
Merging Changes
Merge the changes from your feature branch into the main branch using:
git merge feature_branch
bash -
Deleting the Feature Branch
After merging, delete the feature branch to keep your repository clean:
git branch -d feature_branch
bash
Conclusion
By using git switch
in your workflow, you maintain a clear and explicit history of your branch changes, making it easier for you and your team to understand the actions performed at each step in your Git history. It's a good practice to start using git switch
to benefit from the clarity and explicitness it brings to the Git workflow.
Thanks for reading. If you enjoyed this post, I invite you to explore more of my site. I write about web development, programming, and other fun stuff.