Quick Git Tips#
1. Switch Branches Without Losing Changes#
Problem: Switching branches with uncommitted changes.
Solution: Stash the changes and reapply them later:
For more information on stashing, see git's documentation on stashing.
2. View Commit History Across Branches#
Problem: Viewing a detailed log of commits and branches.
Solution: Git's log
command comes with many options to visualize commit history in a pretty way:
In the handbook, we have a dedicated branch that handles the deployment of the website called gh-pages
.
To avoid seeing this branch in your git log, you can use the following command:
For more information on the log
command, see git's documentation on log.
3. Edit the Last Commit#
Problem: You committed changes but realize you forgot something.
Solution: Amend the last commit with:
This doc by Atlassian does a great job explaining different ways to rewrite history in git.
For more information on git commits and their options, see git's documentation commits.
4. Check for Merge Conflicts#
Problem: Identifying conflicts before merging branches.
Solution: Use a dry-run merge to check for conflicts:
5. Simplify Commands with Aliases#
Problem: Repeatedly typing long Git commands.
Solution: Create shortcuts for common commands:
This allows you to shorten commands like git checkout
to git co
.
You can even add common options to your aliases.
For example, to always use the -m
flag when committing, you can set up an alias like this:
Now to write a commit message, you can use:
You can see all the aliases you have set up by running:
7. Remove local branches that have been deleted remotely#
Problem: You or another lab member have deleted a branch on the
remote repository, but it still shows up in your local repository.
Solution: Use the following command to remove local branches that have been deleted remotely:
This command will remove all local branches that have been deleted on the remote repository.