Unlocking the Power of Git: Tips and Tricks

Git is an indispensable tool in the modern developer’s toolkit. Its powerful version control system and ability to make code more collaborative have made it an industry standard, yet, how much do you really know about git?

Here are some of the more interesting git commands that I’ve accumulated over the years. (Last updated on 6/18/2024)

Undoing Changes

Undo the last commit and keep the changes

git reset --soft HEAD~1

Undo the last commit and discard the changes

git reset --hard HEAD~1

Checkouts

Checkout a certain commit (without detaching HEAD)

git checkout -b <tmp-branch> <commit-hash>

Checkout a specific file form a repo

git checkout <commit-hash> -- <file-path>

Commits

Amend the last commit message

git commit --amend

Branches

Delete a local branch

git branch -d <branch-name>

Delete a remote branch

git branch <remote-name> -d <branch-name>

Logs

Show the the commmit log

git log

Show the commit log in a pretty graph

git log --graph --online --all

Stashes

Stash your changes

git stash

Apply your stashed changes

git stash apply

Submodules

Clone a repo with submodules

git clone --recurse-submodules <path-to-repo>

Add a submodule

git submodule add <path-to-submodule-repo>

Remove a submodule

git rm <path-to-submodule>

Bonus: Bisects

Using bisect to find bugs

# This starts your bisect session
git bisect start    

# Mark the current commit as bad
git bisect bad      

# Specify the commit where the bug was not present.
git bisect good <commit-hash>

# Git will checkout a commit halfway between the 2 specified. It is now up to the user to check that commit.

# IF the commit has the bug, it gets marked as bad
git bisect bad

# If the commit DOES NOT have the bug, it gets marked as good
git bisect good

# Repeat until the bug is found, then end the session
git bisect reset

As a reminder all staff and faculty have access to Swarthmore’s GitHub instance at github.swarthmore.edu