Some Helpful Git Commands and Workflows

Julien Chien
3 min readSep 11, 2017

--

Gitting Gud is a Process

I have gathered some Git commands and workflows that have helped me — hopefully, they will help others as well. For each entry, I’ve added sources if that’s how I learned about that particular command/workflow in the first place, and/or the linked page has good content related to this particular Git command.

I highly encourage the reader actually read those sourced webpages. They frequently have more indepth discussions of the specific problems or issues. Many, especially the linked Stack Overflow questions, contain alternate workflows. They are worth reading just to learn more about Git in general, and alternate commands might be simpler and/or more intuitive to the reader.

There is never just one way to do something in life and in Git.

One Branch To Another

To push a local branch named <A> to a remote branch named <B>:

>git push <remote-name> <A>:<B>

This is useful if you ever branch and create changes which should overwrite another branch.

Source — Stack Overflow

Adding To the Last Commit

Add additional changes to the last commit or change the last commit’s commit message:

Add all changes to staging >git add . Amend the last commit to include changes on staging >git commit --amend

Note — this changes the SHA of the last commit. If you have already pushed the pre-amend last commit upstream, you will have to force push this branch to overwrite (if that is what you want to do).

Source — Nathan Hoad

Reseting Without a Trace

If you committed something on your local branch that you do not want, use git reset:

Resets to the previous commit >git rest HEAD~1

Many Git commands can be used by targeting specific SHAs. For example, git checkout 8072be67 would checkout the version of the repo at commit 8072be67. However, sometimes you just want the commit that’s three before the current version, in which case you would do git checkout HEAD~3. Sometimes you also see git checkout HEAD^1.

The caret (^) references the parents of that commit. Usually, if two or more branches are merged together, they would have multiple parents. So HEAD^1 references the first parent of HEAD, and HEAD^2 references the second parent of HEAD.

The tilde (~) references a commit’s ancestry. HEAD~1 references the first ancestor of HEAD (the first parent of HEAD), and HEAD~2 references the grandparent of HEAD (the first parent of the first parent of HEAD).

Paul Boxley has a more thorough explanation with examples here; there’s also a Stack Overflow discussion here.

Greping with Git

You can also grep with Git:

>git grep <regular expression>

Grepping with Git is potentially faster than normal grep (though it might just be BSD grep being slow).

Further Reading

There is a wealth of Git knowledge out there:

Originally published at wholien.xyz on September 11, 2017.

--

--