Git Switch Branch: Everything You Need to Know

476
CloudBees
CloudBees, the enterprise software delivery company, provides the industry’s leading DevOps technology platform. CloudBees enables developers to focus on what they do best: Build stuff that matters, while providing peace of mind to management with powerful risk mitigation, compliance and governance tools.

The following is a guest blog post written by Carlos Schults.

Repositories in Git work in a fundamentally different way from most other tools. One of the most glaring examples of said differences is branching. In most other VCS tools, branching is this elaborate ceremony. They make a huge deal out of it, and developers just give up, preferring workflows that don’t rely on many branches.

In Git, the opposite is often true: branching is so cheap that most people do it a lot. People often get confused when trying to manage their branches. This post attempts to clear up some of that confusion by offering a guide on how to successfully git switch branch in an easy and safe way. Before we get there, though, we start with some basics, explaining what branches actually are in Git, how they work and how you create them.

Before wrapping up, we share a bonus tip, covering how to check out remote branches. Let’s get started!

How Do Git Branches Work?

How do branches work in Git? The first thing you need to know is that a repository in Git is made up of objects and references. The main types of objects in a Git repository are commits. References point to other references or to objects. The main types of references are—you’ve guessed it—branches.

Objects in Git are immutable. You can’t change a commit in any way or move its position in history. There are commands that appear to change things, but they actually create new commits. References, on the other hand, change a lot. For instance, when you create a new commit, the current branch reference is updated to point to it.

When you create a new branch, all that happens is that a new reference is created pointing to a commit. That’s why it’s so cheap and fast to create branches in Git. Speaking of which…

How Do I Create a New Branch?

We already have a whole post explaining how you can create a branch in Git, covering the four main ways to do that.

Here, we’ll just cover the easiest way to create a branch in Git, which is simply using the branch command from the current branch. Let’s see an example:

mkdir git-switch-demo # creating a folder
cd git-switch-demo
git init # initializing a repository
touch file1.txt # creating the first file
git add . # adding the file to the stage
git commit -m "Create first file" # commiting the file
touch file2.txt
git add .
git commit -m "Create second file"
touch file3.txt
git add .
git commit -m "Create third file"

In the example above, we’ve created a new repository and added three commits to it, creating a new file per commit. Here’s a visual representation of the current state of our repository:

To create a new branch from the current point, we just have to run git branch <branch-name>. I’ll call the branch “example” since I’m not feeling particularly creative:

git branch example

We’ve created a branch but haven’t switched to it yet. This is how our repo looks like now:

What if we added a new commit while still in the master branch? Would that impact the example branch? The answer is no. Execute the following commands:

echo "Another file" > file4.txt
git add .
git commit -m "Create fourth file"

In the next section, we’ll show how you can git switch branch, and then you’ll be able to see for yourself how that new branch doesn’t contain the fourth commit. For now, take a look at the visual representation of the current state of our repo:

How Do You Switch Branches?

For most of Git’s history, the checkout command was used for that. While you can still use it, version 2.23 of Git added the switch command (as well as the restore command) in an attempt to have more specific commands for some of the many tasks the checkout command is used for.

How Do I Use Git Checkout?

The older, more well-know way of switching branches in Git is by using the checkout command. Following our example, if we wanted to change to the “example” branch, we’d just have to run:

git checkout example

After executing the command, you should see a message saying that you’ve successfully switched to the example branch:

Now you’re in the new branch, that means you can add how many commits you want, knowing that the master branch won’t be impacted. The checkout command, followed by a branch name, updates the working tree and the index, and it updates the HEAD reference, pointing it to the branch you’ve just checked out. What if you had uncommitted changes at the moment of switching? Those would be kept to allow you to commit them to the new branch.

Git allows you to use the checkout command in different ways. For instance, an incredibly common scenario is to create a branch and immediately switch to it. In fact, I’d argue that creating a branch and not changing to it on the spot is the exception rather than the rule. So, Git offers us a shortcut. Instead of creating a branch and then checking it out, you can do it in one single step using the checkout command with the -b parameter.

So, doing this:

git checkout -b new

is equivalent to this:

git branch new
git checkout new

Checkout doesn’t work only with branches, though. You can also checkout commits directly. Why would you want to do so?

Well, taking a look at how the project was some amount of time ago is often useful, particularly for testing purposes. But there’s more. Checking out a commit puts your repository in a state called “detached HEAD” {~~~~~~~~ We could create a link here to the “git detached head” post I wrote if it gets published before this one ~~~~~~~~} which allows you to create experimental changes, adding commits that you can then choose to keep or throw away.

What Is Git Switch?

For the most part of Git’s lifetime, the checkout command was the only one you’d use for switching branches. The problem is that this command also does other things, which can lead to confusion, especially among new users.

The 2.23.0 version of Git solves this by adding two new commands: switch and restore. The restore command isn’t relevant for us today. The switch command, on the other hand, is a new way to switch to branches.

The manual page for the command lists all of its many options. On its most basic form, you use it the same way as git checkout, only swapping the command’s name:

git switch example

If you want to go back to the previous branch, you can use a shortcut instead of its full name:

git switch -

What if you want to create a new branch and immediately switch to it? With checkout, we could use this shortcut:

git checkout -b <branch-name>

The new command also offers a shortcut, but in this case, we use the letter “C”:

git checkout -c <branch-name>

Is using the new command worth it? Well, I’ll probably keep using git checkout, as long as they don’t change it, mainly because of muscle memory. But when teaching Git to beginners? Then I’ll definitely use the switch command. It has a name that’s more closely related to the task it does and, therefore, it’s more memorable.

How Do I Switch to a Remote Branch?

Before wrapping up, we share a final tip: how to switch to remote branches?

For this example, we’re going to use an open-source project called Noda Time, which is an alternative date and time API for .NET. Start by cloning the repository:

git clone https://github.com/nodatime/nodatime.git

If everything worked fine, you should have a “nodatime” folder now. Enter the folder and run the following command:

git branch -a

The branch command lists the branches in your repository. The “-a” option means you want to see all branches, not only local ones. The result should look like this:

As you can see, we have only one local branch, which is the master branch. You can see, in red, all of the remote branches. So, let’s say you want to check out the branch called “slow-test.” How would you go about that?

Well, technically speaking, Git doesn’t allow you to work on other people’s branches. And that’s what remote branches are. What you actually do is to create a local “copy” of someone else’s branch to work on. So, let’s see how to do it.

When you create a branch, you can pass a commit or branch name as a parameter. So, in order to create a local branch from the remote “slow-test” branch, I’d just have to do:

git branch slow-test origin/slow-test

In the example, I’m using “slow-test” as the name for my local branch, but I could’ve really used any other valid name.

Alternatively, I could’ve used the checkout command with the -b option or the switch command with the -c option. So, the two following lines are equivalent to the line above:

git checkout -b slow-test origin/slow-test
git switch -c slow-test origin/slow-test

Finally, there’s an even easier way. I could’ve just used git checkout slow-test, and the result would have been the same. That works because when you try to check out a branch and Git doesn’t find a branch with that name, it tries to match it with a remote branch from one of your remotes. If it can successfully match it, things just work.

Git Branches: Use in Moderation

In this post, we’ve shown you how to switch branches in Git. But we went further than that: we’ve explained what branches are and how they work. Hopefully, by now, you’re more comfortable creating and using branches in Git.

Before we go, a final caveat: just because you can do something, it doesn’t mean you should. Sometimes people get so carried away with the ease of branching in Git they end up using workflows that rely on a number of long-lived branches, which makes their development process way too complex and error-prone and delays integration.

Thanks for reading, and until next time.

Carlos Schults is a .NET software developer with experience in both desktop and web development, and he’s now trying his hand at mobile. He has a passion for writing clean and cuuuuoncise code, and he’s interested in practices that help you improve app health, such as code review, automated testing, and continuous build.

CloudBees
CloudBees, the enterprise software delivery company, provides the industry’s leading DevOps technology platform. CloudBees enables developers to focus on what they do best: Build stuff that matters, while providing peace of mind to management with powerful risk mitigation, compliance and governance tools.
Tools mentioned in article
Open jobs at CloudBees
Development Support Engineer
United States or Canada

Our Customers Develop Software at the Speed of Ideas

CloudBees is powering the continuous economy by offering the world’s first end-to-end continuous software delivery management system (SDM). For millions of developers and product teams driving innovation for businesses large or small, SDM builds on continuous integration (CI) and continuous delivery (CD) to enable all functions and teams within and around the software delivery organization to best work together to amplify value creation.
 
CloudBees is the continuous integration (CI), continuous delivery (CD) and application release automation (ARA) powerhouse built from the commercial success of its products and its open source leadership as the largest contributor to Jenkins and a founding member of the Continuous Delivery Foundation (CDF). With a globally distributed workforce of more than 500 employees, the company reflects the global nature of the DevOps movement. We believe in walking the talk! From startups with full-stack developers practicing NoOps to large Fortune 100 companies, CloudBees enables all software-driven organizations to intelligently deploy the right capabilities at the right time.
  
Over 3,500 of the world’s best known brands and over 50% of the Fortune 500, invest in CloudBees because of its ability to work across any cloud, in any development environment and to balance corporate governance and control with developer flexibility and freedom.
 
CloudBees is home to the world’s leading DevOps experts helping thousands of companies harness the power of “continuous everything” and putting them on the fastest path from great idea, to great software, to great business value.

What You’ll Do

Provide software technical support to developers and configuration managers on the CloudBees products. This includes communicating directly with customers via our support portal. This is however, much more than just a “support” position.

  • Ability to analyze scenarios of software implementations and provide solutions for problems
  • Set correct priorities for ongoing issues
  • Work with the CloudBees development team to improve products and/or resolve customer issues
  • Work with other software partners to resolve customer issues
  • At times, work in high pressure situations such as “customer down” priority scenarios to resolve issues timely and professionally
  • The support engineer must be well-rounded in IT skills, the ability to use a wide range of that knowledge at any given time is crucial
  • Capable of working in a fast-paced environment

What The Role Requires

  • Degree in computer science / IT – or – equivalent experience
  • Trouble shooting skills with multi-threaded applications (debugging, analyzing a thread dump, troubleshooting
  • Jenkins user (setting up release processes, for example)
  • Measurable level of experience in multiple operating systems (Windows, Linux, OS X)
  • Measurable level of experience with continuous integration. Jenkins experience preferred
  • Measurable level of experience with Docker, AWS and Configuration Management tools (Chef, Puppet, etc...) 
  • Basic knowledge of shell scripting (CMD, KSH)

What You’ll Get

  • Highly competitive benefits and vacation package
  • Ability to work for one of the fastest growing companies with some of the most talented people in the industry
  • Team outings
  • Fun, Hardworking, and Casual Environment
  • Endless Growth Opportunities

At CloudBees, we truly believe that the more diverse we are, the better we serve our customers. A global community like Jenkins demands a global focus from CloudBees. Organizations with greater diversity—gender, racial, ethnic, and global—are stronger partners to their customers. Whether by creating more innovative products, or better understanding our worldwide customers, or establishing a stronger cross-section of cultural leadership skills, diversity strengthens all aspects of the CloudBees organization.

In the technology industry, diversity creates a competitive advantage. CloudBees customers demand technologies from us that solve their software development, and therefore their business problems, so that they can better serve their own customers. CloudBees attributes much of its success to its worldwide work force and commitment to global diversity, which opens our proprietary software to innovative ideas from anywhere. Along the way, we have witnessed firsthand how employees, partners, and customers with diverse perspectives and experiences contribute to creative problem solving and better solutions for our customers and their businesses.

 

Operations Engineer
Raleigh, NC, Boston, MA, US East

Our Customers Develop Software at the Speed of Ideas

CloudBees is powering the continuous economy by offering the world’s first end-to-end continuous software delivery management system (SDM). For millions of developers and product teams driving innovation for businesses large or small, SDM builds on continuous integration (CI) and continuous delivery (CD) to enable all functions and teams within and around the software delivery organization to best work together to amplify value creation.

 CloudBees is the continuous integration (CI), continuous delivery (CD) and application release automation (ARA) powerhouse built from the commercial success of its products and its open source leadership as the largest contributor to Jenkins and a founding member of the Continuous Delivery Foundation (CDF). With a globally distributed workforce of more than 500 employees, the company reflects the global nature of the DevOps movement. We believe in walking the talk! From startups with full-stack developers practicing NoOps to large Fortune 100 companies, CloudBees enables all software-driven organizations to intelligently deploy the right capabilities at the right time.

Over 3,500 of the world’s best known brands and over 50% of the Fortune 500, invest in CloudBees because of its ability to work across any cloud, in any development environment and to balance corporate governance and control with developer flexibility and freedom.

CloudBees is home to the world’s leading DevOps experts helping thousands of companies harness the power of “continuous everything” and putting them on the fastest path from great idea, to great software, to great business value.

To support the delivery of the CloudBees engineering projects - the Operations team designs, deploys and manages a variety of software systems and the related AWS infrastructure that underpins this software.

CloudBees has an Operations team that is available around the clock (in their respective time zones!) to deliver a highly available service to our growing engineering teams.

One of your first tasks will be to integrate with the engineering teams to deliver the infrastructure required to deploy their projects - “Embedded Ops” - this role helps deliver infrastructure that meets the Engineering project’s needs while conforming to Operations guidelines for long term maintenance and reliability.

What You'll Do

  • Collaborate with existing project operations and CloudBees operations team members to ensure solutions fit into exists patterns.
  • Design, development, integration, testing and delivery of infrastructure for engineering teams.
  • Ongoing operational design and implementation work CloudBees infrastructure
  • Handle operational incidents from initiation to resolution
  • Drive architecture for major feature areas and drive decisions regarding key technologies
  • Troubleshoot and debug software and infrastructural components including application of root cause analysis to find faults.
  • Contribute fixes and enhancements to the open source projects
  • Tuning of monitoring, system design and alerting to reduce alert quantity, increase alert quality and ultimately eliminate alert fatigue.
  • Assist with escalated support incidents
  • Report to the CloudBees IT Operations Manager on status of system faults and deliverables
  • Ability to follow processes and complete work within a change controlled environment

What the Role Requires 

  • Self-motivated and driven personality
  • Excellent problem solving and communication skills
  • Ability to operate independently and ask questions when stuck
  • Well-rounded experience programming in various languages and domains
  • Linux systems administration experience
  • Experience with cloud-based operations (e.g. AWS,  Azure, GCP)
  • Familiarity with the "modern Ops stack", e.g. monitoring, alerting, cloud-based provisioning, Docker.
  • Experience/understanding of configuration management tools
  • Experience/familiarity with modern software engineering practices: code reviews, unit/acceptance testing, source control, etc.
  • Experience with cluster orchestration tools (e.g. Cloud Formation / k8s / ECS / Terraform / etc)
  • Experience with continuous integration / continuous delivery tools (Jenkins / Bamboo / TeamCity etc)

What You’ll Get

  • A highly competitive benefits and vacation package
  • The opportunity to work for one of the fastest growing companies with some of the most talented people in the industry
  • Cool team outings (To Málaga for instance!)
  • Fun, Hardworking, and Casual Environment
  • Endless Growth Opportunities

At CloudBees, we truly believe that the more diverse we are, the better we serve our customers. A global community like Jenkins demands a global focus from CloudBees. Organizations with greater diversity—gender, racial, ethnic, and global—are stronger partners to their customers. Whether by creating more innovative products, or better understanding our worldwide customers, or establishing a stronger cross-section of cultural leadership skills, diversity strengthens all aspects of the CloudBees organization.

In the technology industry, diversity creates a competitive advantage. CloudBees customers demand technologies from us that solve their software development, and therefore their business problems, so that they can better serve their own customers. CloudBees attributes much of its success to its worldwide work force and commitment to global diversity, which opens our proprietary software to innovative ideas from anywhere. Along the way, we have witnessed firsthand how employees, partners, and customers with diverse perspectives and experiences contribute to creative problem solving and better solutions for our customers and their businesses.

Remote DevOps Consultant
United States

Our Customers Develop Software at the Speed of Ideas

CloudBees is powering the continuous economy by offering the world’s first end-to-end continuous software delivery management system (SDM). For millions of developers and product teams driving innovation for businesses large or small, SDM builds on continuous integration (CI) and continuous delivery (CD) to enable all functions and teams within and around the software delivery organization to best work together to amplify value creation.
 
CloudBees is the continuous integration (CI), continuous delivery (CD) and application release automation (ARA) powerhouse built from the commercial success of its products and its open source leadership as the largest contributor to Jenkins and a founding member of the Continuous Delivery Foundation (CDF). With a globally distributed workforce of more than 500 employees, the company reflects the global nature of the DevOps movement. We believe in walking the talk! From startups with full-stack developers practicing NoOps to large Fortune 100 companies, CloudBees enables all software-driven organizations to intelligently deploy the right capabilities at the right time.
  
Over 3,500 of the world’s best known brands and over 50% of the Fortune 500, invest in CloudBees because of its ability to work across any cloud, in any development environment and to balance corporate governance and control with developer flexibility and freedom.
 
CloudBees is home to the world’s leading DevOps experts helping thousands of companies harness the power of “continuous everything” and putting them on the fastest path from great idea, to great software, to great business value.

As a DevOps Consultant, you will be the primary operational point of contact for one or more enterprise customers, helping to plan, review, and monitor ongoing operations of our customers Continuous Delivery pipeline. You will leverage your broad experience, troubleshooting application and architectural challenges to support our customers. You will work across customer organizations to ensure customers’ Continuous Integration (CI) / Continuous Delivery (CD) solution is well designed and scalable to their needs. In this role, you will also act as the voice of the customer within CloudBees to escalate problems and to drive prioritization of business needs for our customers.

What You'll Do

  • Champion and advocate for enterprise customers within CloudBees (be their voice)
  • Solve technical issues and work directly with CloudBees engineers to ensure that customer issues are resolved as expediently as possible
  • Participate in deep architectural discussions, calling on CloudBees subject matter experts as needed, to ensure solutions are designed for successful deployment
  • Help enterprise customers define IT and business processes that work well with CI/CD deployments
  • Engage with Director and C-Level executives to translate business needs into technical and operational plans
  • Provide detailed reviews of service metrics to customer leadership

What The Role Requires

  • Jenkins CI experience required
  • 5+ years in a DevOps, Release Engineering, or Software Engineering role
  • Willingness to learn Docker and MicroServices
  • Experience managing large scale environments including escalations, incident, problem, and service availability
  • Customer-facing experience as a technical lead
  • High level of comfort communicating effectively across internal and external organizations
  • Presentation skills; high degree of comfort with both large and small audiences
  • Bachelor’s degree or equivalent work experience required; Computer Science or Math background highly desired; working knowledge of software development practices and technologies highly desired
  • Software design, development and deployment
  • Occasional travel to visit your customers

What You’ll Get

  • Highly competitive benefits and vacation package
  • Ability to work for one of the fastest growing companies with some of the most talented people in the industry
  • Industry Certifications
  • Team outings
  • Fun, Hardworking, and Casual Environment
  • Endless Growth Opportunities

At CloudBees, we truly believe that the more diverse we are, the better we serve our customers. A global community like Jenkins demands a global focus from CloudBees. Organizations with greater diversity—gender, racial, ethnic, and global—are stronger partners to their customers. Whether by creating more innovative products, or better understanding our worldwide customers, or establishing a stronger cross-section of cultural leadership skills, diversity strengthens all aspects of the CloudBees organization.

In the technology industry, diversity creates a competitive advantage. CloudBees customers demand technologies from us that solve their software development, and therefore their business problems, so that they can better serve their own customers. CloudBees attributes much of its success to its worldwide work force and commitment to global diversity, which opens our proprietary software to innovative ideas from anywhere. Along the way, we have witnessed firsthand how employees, partners, and customers with diverse perspectives and experiences contribute to creative problem solving and better solutions for our customers and their businesses.

Senior Software Engineer
Raleigh, NC, Boston, MA, or

Our Customers Develop Software at the Speed of Ideas

CloudBees is powering the continuous economy by offering the world’s first end-to-end continuous software delivery management system (SDM). For millions of developers and product teams driving innovation for businesses large or small, SDM builds on continuous integration (CI) and continuous delivery (CD) to enable all functions and teams within and around the software delivery organization to best work together to amplify value creation.
 
CloudBees is the continuous integration (CI), continuous delivery (CD) and application release automation (ARA) powerhouse built from the commercial success of its products and its open source leadership as the largest contributor to Jenkins and a founding member of the Continuous Delivery Foundation (CDF). With a globally distributed workforce of more than 500 employees, the company reflects the global nature of the DevOps movement. We believe in walking the talk! From startups with full-stack developers practicing NoOps to large Fortune 100 companies, CloudBees enables all software-driven organizations to intelligently deploy the right capabilities at the right time.
  
Over 3,500 of the world’s best known brands and over 50% of the Fortune 500, invest in CloudBees because of its ability to work across any cloud, in any development environment and to balance corporate governance and control with developer flexibility and freedom.
 
CloudBees is home to the world’s leading DevOps experts helping thousands of companies harness the power of “continuous everything” and putting them on the fastest path from great idea, to great software, to great business value.

What You’ll Do

  • Collaborate with product management, support and engineering teams in order to define priorities and roadmaps
  • Support and enhance the Jenkins experience for our customers by way of its rich plugin system
  • Work as a contributor in the Jenkins open-source community, deliver fixes and enhancements to the Jenkins open source project specifically around the various plugins
  • Collaborate with CloudBees customers when needed to help define requirements and help them solve challenging issues
  • Collaborate with the Jenkins Security Team to cross reference the priorities of items to address

What The Role Requires

  • 5+ years experience developing with Java.
  • Demonstrated implementation of microservices, container and cloud-native application development.
  • Hands-on experience with Docker, Kubernetes or Openshift and related container platform ecosystems.
  • Strong understanding and experience of release engineering and continuous delivery process
  • Strong understanding of static code analysis, unit testing and test driven development, security testing and automated test frameworks.
  • Experience using Jenkins, SonarQube, GIT, Maven.
  • Solid understanding of Amazon Web Services; Azure, Google Cloud a plus.
  • Nice to have: contributions to the Jenkins Project or Jenkins plugins
  • Knowledge of developer tools such as Continuous Integration/Continuous Delivery systems, test tools, code quality tools, planning tools, IDEs and debugging tools
  • Excellent problem solving and communication skills
  • Ability to be self sufficient given the proper guidance
  • Fully proficient in English written and spoken language
  • Comfortable working closely with support, customers and community to help resolve issues

Why CloudBees?

  • We build our business on Jenkins by offering enterprise solutions (CloudBees CI) and professional services, our customers range from the blue chips to small innovative companies
  • We work on various projects in different areas. We are flexible about changing teams and assignments according to the interest and passion of engineers.
  • Our Engineering teams are distributed by design. You can work from the office or remotely without feeling disconnected.
  • You have an opportunity to contribute to open-source projects and communities during your working time.
  • We offer an attractive benefits package including stock options.

What You’ll Get

  • Highly competitive benefits and vacation package
  • Ability to work for one of the fastest growing companies with some of the most talented people in the industry
  • Team outings
  • Fun, Hardworking, and Casual Environment
  • Endless Growth Opportunities

At CloudBees, we truly believe that the more diverse we are, the better we serve our customers.  A global community like Jenkins demands a global focus from CloudBees. Organizations with greater diversity—gender, racial, ethnic, and global—are stronger partners to their customers.  Whether by creating more innovative products, or better understanding our worldwide customers, or establishing a stronger cross-section of cultural leadership skills, diversity strengthens all aspects of the CloudBees organization.

In the technology industry, diversity creates a competitive advantage.  CloudBees customers demand technologies from us that solve their software development, and therefore their business problems, so that they can better serve their own customers.  CloudBees attributes much of its success to its worldwide work force and commitment to global diversity, which opens our proprietary software to innovative ideas from anywhere. Along the way, we have witnessed firsthand how employees, partners, and customers with diverse perspectives and experiences contribute to creative problem solving and better solutions for our customers and their businesses.

You may also like