Current section: Commands 17 exercises

Branch Management and Syncing with Git and GitHub

The git switch command is used to to create and switch branches.

Running git switch without any arguments will show that we don't have any branches to switch to:

$ git switch
fatal: missing branch or commit argument

We can create and switch to a branch in a single command with the

Loading lesson


00:00 Use git switch to create and switch branches. Here, I didn't define a branch to switch to, and that's because we have no branches to switch to. I can create and switch to a branch using a single command with the C option and naming my branch. Running git status, we see for the first time that we are on

00:19 a non-main branch and running git log, we can see where this branch diverges from main. Let's do a couple of things on this branch. Run git push to push it up to the remote repository. We get an error, but it's an extremely helpful error. It actually gives us the command that we can use to set up

00:38 an origin branch that's connected to this local branch. If we don't want to do that every time, it gives us an option for the configuration we can use to have it set up automatically. There's no time like the present, so let's add that config. Now, if we run git push again, git will automatically set up a tracking branch

00:58 for us using the same name. My branch is tracked to origin my branch. Over in GitHub, our remote repository, hit refresh and see that in addition to our main branch, we now have a my branch as well. Let's add one final file for git branch.

01:16 Add it to our index and commit it. Run git status to see that we are ahead of our origin, which we can fix by typing git push. Seeing an automatic refresh on the GitHub side, and run git log to see what's happening locally. We're currently on this commit, where my branch and origin my branch are in sync,

01:35 but we're ahead of main and origin main. Let's switch back to main and merge everything from my branch back in to the main branch. Run git log again to see that main is now in sync with origin my branch and my branch, but origin main isn't. Easy fix, we run git push to push

01:54 that last commit to our origin main. Now, all of our branches are in sync again.