Frequently Used Git Commands
Apr 5, 2021 11:06 AM
Updated At
Apr 8, 2021 01:54 PM
There are some questions I find myself repeatedly searching for the answer for in Git. Below I'll capture those repeated questions and their answer! It will certainly help me, and I hope it will help you.

How can I rename a branch?

# The -m is the important part here!
# I read the below as "git branch move to newname"
git branch -m newname

How can I move commits from master/main to a new branch?

git branch newbranch
# Go back 3 commits. This could be any number. You *will* lose uncommitted work.
# You can also specify a commit ref
git reset --hard HEAD~3
git checkout newbranch

I ran git clean and now my code is gone. Can I get it back?

Maybe. I highly recommend reading this SO post, and also this one. Here are the take-away commands:
git fsck --cache --no-reflogs --lost-found --dangling HEAD
# Then show the file
git cat-file blob <SHA> > filename.txt
# Get list of unreachable files that git knows a file name for
git fsck --unreachable --no-reflogs --no-cache HEAD | fgrep " tree " | cut -d " " -f3 | xargs -r -n1 git ls-tree | fgrep " blob " | cut -d " " -f 3- | sort -k2 -u