Git Basics: Creating a Branch and Merging It
A branch is a movable name for a commit. It lets you develop a change separately, then bring that work into another branch when it is ready.
Run these commands in Bash with Git 2.28 or newer installed. Each article starts in a fresh temporary repository; no remote account is needed.
git_practice=$(mktemp -d) || exit
cd "$git_practice" || exit
git init -q -b main
git config user.name 'Practice User'
git config user.email 'practice@example.invalid'
git config commit.gpgsign falseThese settings apply only to this repository; signing is disabled for the exercise. Use your own identity in real projects. The temporary files remain after the exercise.
Start from one commit
printf 'port=8080\n' > app.conf
git add app.conf
git commit -q -m 'Add application config'
git switch -q -c change-port
printf 'port=9090\n' > app.conf
git add app.conf
git commit -q -m 'Change application port'
git branch --show-currentchange-portgit switch -c creates the branch and switches to it. The new commit moves change-port forward; main still points to the original commit.
Return to main
git switch -q main
cat app.confport=8080Switching updates the working files to match the selected branch. Commit or otherwise preserve unfinished work before switching: local edits can carry across branches, or Git may refuse a switch that would overwrite them.
Merge the change
git merge -q --ff-only change-port
cat app.confport=9090This succeeds because main has no separate commits since the branch was created. Git can move main straight forward to the same commit as change-port. This is a fast-forward and creates no merge commit.
--ff-only refuses the merge if the histories have diverged. If that happens in a real project, inspect both histories and choose the team’s merge or rebase workflow rather than forcing an update.
After checking the result, remove the merged local branch name:
git branch -d change-portGit prints a deletion confirmation with a commit ID that varies. The commit remains reachable through main. None of these steps creates a pull request or updates a remote repository.
Reference
Acknowledgements
This post was created with assistance from AI.