Advanced Git Techniques
1. Understanding Git Rebase
Git rebase is a powerful command that allows you to integrate changes from one branch into another by reapplying commits on top of another base tip. Unlike merge, which creates a new commit that combines changes from both branches, rebase rewrites the commit history.
To perform a rebase, you can use the following command:
Example:
git rebase main
This process will take the commits from your feature-branch
and apply them on top of the main
branch.
2. Interactive Rebase
Interactive rebase allows you to not only rebase your commits, but also edit, squash, or reorder them. This is useful for cleaning up commit history before merging changes.
To start an interactive rebase, use the following command:
Example:
This command opens an editor with the last three commits, allowing you to choose operations like rewording, squashing, or dropping commits.
3. Git Cherry-Pick
Cherry-picking allows you to apply the changes introduced by some existing commits. This is useful when you want to apply specific changes from one branch to another without merging the entire branch.
To cherry-pick a commit, use:
Example:
git cherry-pick abc123
This command applies the changes from commit abc123
onto the current branch.
4. Stashing Changes
Stashing is a way to temporarily save changes that are not ready to be committed. You can stash changes and apply them later, which is useful for keeping your working directory clean.
To stash your changes, use:
To apply stashed changes, use:
Example:
git stash apply
You can also view your stash list with:
5. Managing Remote Repositories
Managing remote repositories is an essential part of working with Git. You can add, remove, and update remote repositories using the following commands:
To add a remote repository:
To remove a remote:
To update a remote's URL:
Example:
6. Git Hooks
Git hooks are custom scripts that Git executes before or after events such as commits, merges, and pushes. These hooks can be used to enforce rules or automate tasks.
For example, to create a pre-commit hook:
chmod +x .git/hooks/pre-commit
You can add your custom script in the pre-commit
file. This script will run every time you commit to the repository.
7. Using Git Tags
Git tags are used to mark specific points in history as important. They are often used for marking release versions. You can create a tag using:
To push tags to a remote repository:
Example:
git push origin v1.0
8. Resolving Merge Conflicts
Merge conflicts occur when changes from different branches overlap. To resolve merge conflicts, you need to manually edit the files that have conflicts, then mark them as resolved with:
After resolving conflicts, you can finalize the merge with:
Example:
# Resolve conflicts in files
git add resolved_file.txt
git commit