Git Switch Branch: Everything You Need to Know

885
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” 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 concise 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
Lead DevOps Engineer
US East or EMEA

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.

WHO WE ARE

The team you will be working on is responsible for making the CloudBees CI releases happen, using CloudBees CI, in a predictable and uneventful way.

Our team aims at being a catalyzer rather than a gatekeeper. For this, we provide and continuously improve automation and tooling so developers can self serve and we deliver value iteratively to customers in a fast and safe manner.

WHAT YOU'LL DO

  • Work in a rapidly iterating team in an agile environment to provide incremental features to the internal (software engineering team) and external customers 
  • Support critical applications and infrastructure, able to troubleshoot independently and create novel solutions
  • Work closely with related teams in the company to bring a culture of automation and self-service, in an inclusive and thoughtful manner
  • Streamline software development by implementing reusable tooling for CI/CD pipelines and automating manual processes and associated developer tooling
  • Participate in code review process, challenging others to be excellent
  • Mentor more junior team members
  • Continuously assess our pipelines and drive changes that will improve cycle times, decrease failure rates, reduce recovery times and remove complexity
  • Incorporate developer requests and suggestions in the design and improvement of our pipelines

WHO YOU ARE

  • BS in Engineering, Computer Science or related fields, or equivalent experience
  • Expert in Jenkins
  • 5+ years of software engineering and related experience in implementing devops practices.
  • Strong experience in implementing end-to-end devops pipelines, especially pipeline creation/management for CI/CD, continuous testing, deployment automation, leveraging pipeline automation, and custom job creation
    • Nice to have: experience orchestrating cloud resources with Terraform
  • Docker / container orchestration experience
  • Experience working in one of the various cloud providers – AWS or GCP
  • Strong interpersonal & leadership skills, and ability to deliver impactful changes that largely go beyond the team’s boundaries
  • Java language knowledge is a plus

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.

Senior DevOps Consultant - Profession...
EMEA

OUR CUSTOMERS DEVELOP SOFTWARE AT THE SPEED OF IDEAS

CloudBees is the continuous integration (CI), continuous delivery (CD) and application release automation (ARA) powerhouse built from the commercial success of its products and a founding member of the Continuous Delivery Foundation (CDF). With a globally distributed workforce of more than 450 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 the home for leading DevOps experts helping thousands of companies harness the power of “continuous everything” and putting them on the fastest path from great ideas, to great software, to great business value.

As a Senior Consultant, you will be working with our clients on how to overcome problems and inefficiencies with their software development and deployment processes. You will leverage your broad experience, troubleshooting abilities and architectural knowledge to implement the best approach to get the  best value from their investment in CloudBees technology. In the implementation process you will lead, architect and execute based on CloudBees proven delivery methodology. 

WHAT YOU’LL DO

  • Provide expert advice on all things related to CI, CD, and Release Management
  • Assess and make technical recommendations for customers to reach their DevOps targets
  • Help customers implement CloudBees products to enable Continuous Integration, Continuous Delivery and Release Management capabilities
  • Provide technical thought leadership for organizations and expert advice related to software design, architecture, and tooling as it relates to improving software delivery across the enterprise
  • Implement CloudBees automation and tracking tooling to help organizations gain true enterprise wide visibility and automation
  • Implement workflows and capabilities to drive towards everything as code

WHAT THE ROLE REQUIRES

  • Experience in fast-moving automated release environments using a variety of tools across configuration management, infrastructure orchestration, and IT Service Management
  • Direct experience in release engineering
  • Deep understanding of enterprise application design, dependencies, as well as modern and legacy applications architecture
  • Knowledge of Enterprise Architecture and the compliance and security concerns related to software development and deployment
  • Understanding of Release Management,  Continuous Integration and Continuous Delivery ecosystems and requirements
  • An understanding of Value Stream Management and process design
  • Practical experience with REST API, SOAP, Perl, Python, Groovy
  • Experience with Release Orchestration and Deployment Automation technology
  • Understanding of Agile development methods and how organizations adopt and implement these to support their end-to-end software development lifecycle processes
  • Strong written and verbal communication skills
  • Proven experience of Cloud providers such as AWS,Google and and Azure
  • Experience with of containers and Kubernetes implementations on major cloud providers and Openshift
  • Experience of training or mentoring others
  • Strong analytical and problem-solving skills
  • Travel- 75% (includes both customer and internal related travel)

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.

 

Senior DevOps Consultant-Professional...
US

OUR CUSTOMERS DEVELOP SOFTWARE AT THE SPEED OF IDEAS

CloudBees is the continuous integration (CI), continuous delivery (CD) and application release automation (ARA) powerhouse built from the commercial success of its products and a founding member of the Continuous Delivery Foundation (CDF). With a globally distributed workforce of more than 450 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 the home for leading DevOps experts helping thousands of companies harness the power of “continuous everything” and putting them on the fastest path from great ideas, to great software, to great business value.

As a Senior Consultant, you will be working with our clients on how to overcome problems and inefficiencies with their software development and deployment processes. You will leverage your broad experience, troubleshooting abilities and architectural knowledge to implement the best approach to get the  best value from their investment in CloudBees technology. In the implementation process you will lead, architect and execute based on CloudBees proven delivery methodology. 

WHAT YOU’LL DO

  • Provide expert advice on all things related to CI, CD, and Release Management
  • Assess and make technical recommendations for customers to reach their DevOps targets
  • Help customers implement CloudBees products to enable Continuous Integration, Continuous Delivery and Release Management capabilities
  • Provide technical thought leadership for organizations and expert advice related to software design, architecture, and tooling as it relates to improving software delivery across the enterprise
  • Implement CloudBees automation and tracking tooling to help organizations gain true enterprise wide visibility and automation
  • Implement workflows and capabilities to drive towards everything as code

WHAT THE ROLE REQUIRES

  • Experience in fast-moving automated release environments using a variety of tools across configuration management, infrastructure orchestration, and IT Service Management
  • Direct experience in release engineering
  • Deep understanding of enterprise application design, dependencies, as well as modern and legacy applications architecture
  • Knowledge of Enterprise Architecture and the compliance and security concerns related to software development and deployment
  • Understanding of Release Management,  Continuous Integration and Continuous Delivery ecosystems and requirements
  • An understanding of Value Stream Management and process design
  • Practical experience with REST API, SOAP, Perl, Python, Groovy
  • Experience with Release Orchestration and Deployment Automation technology
  • Understanding of Agile development methods and how organizations adopt and implement these to support their end-to-end software development lifecycle processes
  • Strong written and verbal communication skills
  • Proven experience of Cloud providers such as AWS,Google and and Azure
  • Experience with of containers and Kubernetes implementations on major cloud providers and Openshift
  • Experience of training or mentoring others
  • Strong analytical and problem-solving skills
  • Travel- 75% (includes both customer and internal related travel)

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.



Front End Engineer-Feature Management
US East or EMEA

OUR CUSTOMERS DEVELOP SOFTWARE AT THE SPEED OF IDEAS

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. Used by many of the Fortune 100, CloudBees is helping thousands of companies harness the power of continuous everything and gets them on the fastest path from a great idea, to great software, to amazing customer experiences, to being a business that changes lives.

Backed by Matrix Partners, Lightspeed Venture Partners, Verizon Ventures, Delta-v Capital, Golub Capital, and Unusual Ventures, CloudBees was founded in 2010 by former JBoss CTO Sacha Labourey and an elite team of continuous integration, continuous delivery, and DevOps professionals.

This role is for a full stack engineer to help us develop the next iteration of CloudBees Feature Flag Management, build new capabilities on top of the existing solution and improve the product to make it simpler to use.  As a developer you are in a unique position to influence the product requirements and priorities. The tool being used by the team is to manage our own features and rollouts and the designated audience for a feature flagging solution is exactly the full stack engineer persona. You will also collaborate with other teams in CloudBees and contribute to our core commercial products. You’ll have a chance to share your expertise with internal and external audiences by blogging, speaking at conferences, hosting webinars, and publishing tutorials.

What You’ll Do

  • Build system to allow our customer to seamlessly rollout features quickly and safely 
  • Collaborate with product management, support and engineering teams in order to define priorities and roadmaps, and support our customers using CloudBees Feature Flag Management
  • Collaborate with customers, partners and community to design and build CloudBees Feature Flag Management and the CloudBees Suite
  • Collaborate with designers as well as engineers on other teams to continuously evolve and improve our internal component library

Why CloudBees?

  • We build our business on software delivery,  by offering enterprise solutions and professional services, our customer 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.
  • We offer an attractive benefits package including stock options.

What The Role Requires

  • 5+ years experience developing more than one language, fluency with JavaScript and TypeScript is required
  • Experience with React/Redux frontend development 
  • Experience working with Kubernetes, Docker, and the cloud native ecosystem is a benefit
  • Experience with Bootstrap, React Bootstrap and good understanding of the internal workings of these specific or similar frameworks
  • A focus on teamwork and supporting your peers
  • Ability to communicate highly complex technical concepts to external partners, including Sales, Customer Support, and Marketing
  • Knowledge of developer tools such as Continuous Integration/Continuous Delivery systems, test tools, code quality tools, planning tools, IDEs and debugging tools
  • Self-motivated and driven personality. Experience working in a remote environment is a plus.
  • Fully proficient in English written and spoken language

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

We have a culture of movers and shakers and are leading the way for everyone else with a vision to transform the industry. We are authentic in who we are. We believe in our abilities and strengths to change the world for the better. Being inclusive and working together is at the heart of everything we do. We are naturally curious. We ask the right questions, challenge what can be done differently and come up with intelligent solutions to the problems we find. If that’s you, get ready to bee impactful and join the hive.

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