Git Branching
A branch in Git is essentially a unique set of code changes with a unique name. Each repository can have one or more branches. The main branch (historically called 'master') is the "default" branch when you create a repository. Use other branches for development and merge them back to the main branch upon completion.
Importance and Scenario
Imagine you're developing a website. You need to work on two features, but you want to keep your work separate for each feature. This is where Git branches come in. You can create a branch for each feature and work on them separately. Once you're done with a feature, you merge it back into your main branch.
Procedure to Create a New Branch, Commit, Merge, and Delete
Here's a step-by-step guide:
- Create a New Branch
git checkout -b feature_branch
This command creates a new branch named 'feature_branch' and switches to it. - Create a File and Commit on New Branch
echo "Hello, World!" > hello.txt
git add hello.txt
git commit -m "Add hello.txt"
This creates a new file 'hello.txt', stages it for commit, and commits it with a message. - Merge New Branch with Main Branch
First, switch back to the main branch:
git checkout main
Then, merge the feature branch with the main branch:
git merge feature_branch
This merges 'feature_branch' into 'main'. - Delete the Feature Branch
git branch -d feature_branch
This deletes the 'feature_branch'.
Remember to replace 'feature_branch' and 'main' with your branch names. Also, ensure you've committed any changes on your current branch before switching branches, or those changes may be lost.