6. Advanced Git Topics

Rebasing (git rebase)

Rebasing is a process of moving or combining a sequence of commits to a new base commit. It's a way to integrate changes from one branch into another, but unlike merging, it does so by reapplying the commits.

Usage:

  1. Switch to the branch you want to rebase:

    
    git checkout feature-branch
    
  2. Start the rebase process:

    
    git rebase master
    

This will take the changes made in feature-branch and reapply them on top of master. The result is a linear history.

Note: Rebasing rewrites history, which can be problematic for shared branches. It's recommended to use rebasing only for branches that haven't been pushed to a remote repository or shared with other collaborators.

Stashing (git stash)

Stashing allows you to temporarily save changes that you don't want to commit immediately. It's useful when you need to switch branches but aren't ready to commit your current changes.

Usage:

  1. To stash your changes:

    
    git stash
    
  2. To apply your stashed changes:

    
    git stash apply
    
  3. To list all stashes:

    
    git stash list
    
  4. To drop a stash:

    
    git stash drop stash@{n}
    

Where n is the stash number.

Interactive commits (git commit --interactive)

Actually, the correct command for interactive staging is git add --interactive (or git add -i). This mode allows you to interactively choose hunks of patch between the index and the working tree.

Usage:

  1. Start the interactive staging:

    
    git add --interactive
    
  2. Follow the prompts to choose patches of changes to stage.

Cherry-picking (git cherry-pick)

Cherry-picking allows you to apply changes from specific commits without merging an entire branch. It's useful when you want to take just one or two commits from a feature branch and apply them to your main branch.

Usage:

  1. Find the commit hash of the commit you want to cherry-pick. You can use git log to view commit hashes.

  2. Use the cherry-pick command followed by the commit hash:

    
    git cherry-pick commit-hash
    

If there are conflicts, you'll need to resolve them. Once resolved, you can continue the cherry-pick process with:


git cherry-pick --continue

Note: Like rebasing, cherry-picking can rewrite commit history. It's essential to use it judiciously, especially with commits that have been shared with others.

Last updated