When developing a new feature, writing code directly on your primary branch risks breaking your working application. Git branches solve this by allowing you to isolate changes and test ideas without altering your production code.
This guide covers how to check, create, and merge local branches using the terminal.
Prerequisites
Git requires at least one commit in a repository before it can track or display branches. Run the following commands to create a project directory, initialize Git, and generate a root commit:
mkdir git-blog-post && cd git-blog-post
git init
git branch -m main
echo "Base project structure" > README.md
git add .
git commit -m "Initial commit"
With an established commit history, you can now begin managing branches.
Step 1: Check Your Active Branch
Before running modifications, verify which branch you are currently working on. Run the following command:
git branch
This command lists all local branches in the repository. The branch marked with an asterisk (*) is your active workspace.
Step 2: Create and Switch to a New Branch
To isolate your new workflow, create a separate branch. Run this command to create a branch named feature-test and switch to it immediately:
git checkout -b feature-test
The -b flag is an operational shortcut. It combines two separate steps: creating the new branch (git branch feature-test) and changing your active workspace to it (git checkout feature-test).
Step 3: Stage and Commit Changes
Create a file to simulate a project modification, stage it, and commit it to your active branch history:
echo "This is a new feature test." > sample.txt
git add sample.txt
git commit -m "Testing a new feature"
This commit is now recorded exclusively on the feature-test branch history. Your main branch remains unchanged.
Step 4: Merge Changes Back to Main
Once your feature changes are ready, integrate them back into your primary production branch. First, switch back to your main branch:
git checkout main
Now, pull the history from feature-test into main using the merge command:
git merge feature-test
Because main had no conflicting changes, Git performs a fast-forward merge, directly updating the main branch pointer to match the latest commit from your feature branch.
Conclusion
Isolating your work in branches keeps your primary codebase stable and organizes your development history. With these four foundational commands, you can safely manage local development workflows directly from the terminal.




Top comments (0)