Git Switch Branch: Everything You Need to Know

966
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
Security Software Engineer in Jenkins...
US East or EMEA

About CloudBees

CloudBees provides the leading software delivery platform for enterprises, enabling them to continuously innovate, compete, and win in a world powered by the digital experience. Designed for the world's largest organizations with the most complex requirements, CloudBees enables software development organizations to deliver scalable, compliant, governed, and secure software from the code a developer writes to the people who use it. The platform connects with other best-of-breed tools, improves the developer experience, and enables organizations to bring digital innovation to life continuously, adapt quickly, and unlock business outcomes that create market leaders and disruptors.

CloudBees was founded in 2010 and is backed by Goldman Sachs, Morgan Stanley, Bridgepoint Credit, HSBC, Golub Capital, Delta-v Capital, Matrix Partners, and Lightspeed Venture Partners. Visit www.cloudbees.com and follow us on Twitter, LinkedIn, and Facebook.

Why this role

We are looking for a highly motivated (security) engineer to join a team focusing on improving the security of Jenkins and CloudBees CI, our Jenkins based product.

What You’ll Do

  • Learn the internals of Jenkins and its plugin system from the perspective of web application security
  • Participate in the Jenkins security team working on the full lifecycle of vulnerabilities
  • Different security aspects: architecture, design, review, implementation
  • Engineer and automate our security tooling/process
  • Security education / awareness
  • Our Engineering teams are distributed by design. You can work from the offices or remotely without feeling disconnected

What The Role Requires

  • Solid experience in Java web application development (JavaScript is a plus)
  • Interest in web application security
  • Experience in scripting is a plus (Groovy, Shell, Python)
  • Hacker mindset
  • Experience using CI/CD tools (Jenkins 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.

Head of Security Engineering
United Kingdom

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.

Why This Position?

This specific opening for an engineering management role was created because of our growth in product offerings, greater velocity of new feature delivery and customer communications. We recognize that a skilled engineering management leader with experience working in other organizations that have gone through rapid growth can have a transformative impact on the success of our product initiatives in the market.

What You’ll Do

  • Own the execution and delivery of security engineering projects
  • Establish and execute on goals for the engineering team by becoming a trusted leader and advisor
  • Plan and lead Agile Sprints and other ceremonies for a high growth/high performance engineering team
  • Focus on hiring and retaining top talent for your team
  • Work closely with your peers in the engineering to coordinate activities related to new product and feature delivery across the product, field and marketing organizations
  • Ensure that new products and features are successfully launched into the market and achieve their goals for awareness, adoption and revenue
  • Continuously communicate status and plans for new product/feature delivery and GTM activities across the organizations
  • Identify and drive resolution of roadblocks and issues that impact the success of new product and feature delivery
  • Provide leadership for a high-performing software engineering team by:
    • Performance appraisal and feedback
    • Setting goals and establishing metrics and accountability
    • Coaching and mentoring
    • Career growth guidance/assistance
    • Recruiting and hiring engineers
    • Facilitation of knowledge and expertise sharing among team members
    • Mediation and conflict resolution
    • Advocate for needs and concerns of team members

What The Role Requires

  • Demonstrated success in leading 5 or more people, including remote engineers, in enterprise software. Preferably in a Tech Lead or Architect or ScrumMaster capacity
  • Recent experience in software development - must feel very comfortable and up to date with coding  
  • Prior hands-on experience writing Java code and doing code reviews
  • 5+ years of experience developing distributed, multi threaded Java applications
  • Deep knowledge of Core Java and RDBMS is a must 
  • Solid experience with Spring and Hibernate frameworks is a big plus
  • Hands on experience with cloud native continuous delivery tools.
  • Familiarity with modern software development practices including agile, DevOps, and continuous delivery, open-source
  • Experience in coordinating activities across all software functions including engineering, product management, product marketing, support, etc.
  • Proficiency with Software Development practices, Java, Cloud, Kubernetes, Jira, etc.  
  • Superior written and verbal communication skills
  • Talent for leading through influence and inspiring high achievement

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
  • High-functioning remote-first culture with a diverse team of co-workers located around the world
  • 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
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.

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

  • Knowledge of and experience with current DevOps industry practices
  • Understanding of REST API, SOAP, Perl, Python, Groovy
  • Strong Linux command line knowledge
  • Strong software architecture knowledge
  • Conducts solution analysis, testing, and provides guidance on common industry practices and technologies
  • Able to collaborate with multiple cross-functional groups at once
  • Working knowledge of SDLC pipeline functions including CI, build methods, code scanning, testing, artifact repositories, release management, deployment automation and infrastructure platforms
  • Can model SDLC to describe the process from concept to delivered solution
  • Able to coordinate and conduct discovery and analysis of current state including process, culture and technology capabilities
  • Can collate and refine detailed functional and nonfunctional requirements in order to inform future state design

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.

 

DevOps Implementation Consultant Nort...
US Central/West

About CloudBees

CloudBees provides the leading software delivery platform for enterprises, enabling them to continuously innovate, compete, and win in a world powered by the digital experience. Designed for the world's largest organizations with the most complex requirements, CloudBees enables software development organizations to deliver scalable, compliant, governed, and secure software from the code a developer writes to the people who use it. The platform connects with other best-of-breed tools, improves the developer experience, and enables organizations to bring digital innovation to life continuously, adapt quickly, and unlock business outcomes that create market leaders and disruptors.

CloudBees was founded in 2010 and is backed by Goldman Sachs, Morgan Stanley, Bridgepoint Credit, HSBC, Golub Capital, Delta-v Capital, Matrix Partners, and Lightspeed Venture Partners. Visit www.cloudbees.com and follow us on Twitter, LinkedIn, and Facebook.

YOU’LL DO

  • Assess and make technical recommendations aligned to supporting clients’ desired outcomes
  • Provide expert advice on CI, CD, and Release Management processes
  •  Implement CloudBees products to orchestrate Continuous Integration, Continuous Delivery and Release Management capabilities supporting both functional and non-functional requirements
  • Develop client specific dashboards and reports in order to provide visibility into their software development value streams  Implement workflows and capabilities to drive towards everything as code

WHAT THE ROLE REQUIRES

  • Experience in  developing, and advising on, automated release environments using a variety of tools across configuration management, testing, infrastructure orchestration, and IT Service Management
  • Understanding of Release Management,  Continuous Integration and Continuous Delivery ecosystems and requirements
  • 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
  • An understanding of Value Stream Management and process design
  • Practical experience with REST API, SOAP, Perl, Python, Groovy
  • 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 Azure
  • Experience with containers and Kubernetes implementations on major cloud providers Experience in training or mentoring others
  • Strong analytical and problem-solving skills
  • Travel - 60% (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.

Verified by
Technical Evangelist
You may also like