Advanced Git Techniques
1. Rebasing
Rebasing is a powerful technique that allows you to integrate changes from one branch into another. Unlike merging, which creates a new commit, rebasing rewrites the commit history.
To rebase your current branch onto another branch, use the following command:
This will take all the commits from your current branch and replay them on top of the specified branch.
Be cautious while rebasing, especially if you have already pushed your commits to a shared repository, as it can create conflicts.
2. Cherry Picking
Cherry picking allows you to select specific commits from one branch and apply them to another. This is useful when you want to merge only certain changes.
To cherry-pick a commit, you can use the command:
This applies the changes from the specified commit to your current branch.
3. Stashing Changes
Stashing is a way to save your uncommitted changes temporarily without committing them. This is useful when you need to switch branches but aren't ready to commit your changes.
To stash your changes, use:
To list your stashed changes:
To apply the latest stash, use:
4. Git Hooks
Git hooks are scripts that run automatically at certain points in the Git workflow. They can be used to enforce policies, automate tasks, and more.
Hooks are located in the .git/hooks directory of your repository. Common hooks include pre-commit, post-commit, and pre-push.
Make sure to give it executable permissions:
You can then add your script inside this file to run checks before each commit.
5. Interactive Rebase
Interactive rebase allows you to edit commit history in a more granular way. You can squash commits, edit commit messages, or drop commits altogether.
To start an interactive rebase, use:
This opens an editor where you can choose how to handle each commit.
In the editor, you can change pick to squash to combine commits or edit to modify a commit.
6. Managing Remotes
Git allows you to manage multiple remote repositories. You can add, remove, and view remotes using the following commands:
This is useful when working with forks or collaborating with others.