To practice git merge and git rebase commands in a single file, follow these steps. This guide assumes you have Git installed and a repository initial

To practice git merge and git rebase commands in a single file, follow these steps. This guide assumes you have Git installed and a repository initial

·

2 min read

Setup for git merge and git rebase

1. Initialize a Git Repository

mkdir merge-rebase-test
cd merge-rebase-test
git init

2. Create a File and Make Initial Commit

echo "Line 1: Initial content" > test.txt
git add test.txt
git commit -m "Initial commit with test.txt"

3. Create and Switch to a New Branch

git branch feature
git checkout feature

4. Modify the File in the feature Branch

echo "Line 2: Added in feature branch" >> test.txt
git add test.txt
git commit -m "Added Line 2 in feature branch"

5. Switch Back to master and Modify the File

git checkout master
echo "Line 2: Added in master branch" >> test.txt
git add test.txt
git commit -m "Added Line 2 in master branch"

Using git merge

6. Merge the feature Branch into master

git merge feature

If there are conflicts, Git will notify you. Open the file, resolve conflicts, and commit the merge:

nano test.txt  # Resolve conflicts manually
git add test.txt
git commit -m "Resolved merge conflicts and completed merge"

Using git rebase

7. Reset the Repository to Before Merge

To test git rebase, reset the repository to before the merge:

git reset --hard HEAD~1

8. Rebase the feature Branch onto master

git checkout feature
git rebase master

If there are conflicts during the rebase:

  1. Resolve the conflicts in the file (test.txt).

  2. Stage the resolved file

  3.  git add test.txt
    

3.Continue the rebase:

  1.  git rebase --continue
    

    Verify the Final State

    9. Switch Back to master and Merge Again

    After rebasing, merge the feature branch back into master:

git checkout master
git merge feature

Summary of Commands

  1. git merge combines changes from two branches, keeping the history intact.

  2. git rebase rewrites the commit history to apply changes sequentially on top of another branch.

You can now compare how merge and rebase affect the Git history using:

git log --graph --oneline --all