Skip to content

Instantly share code, notes, and snippets.

@benwtks
Last active April 25, 2023 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benwtks/b243adebb9154f9edc2725f72ce4071a to your computer and use it in GitHub Desktop.
Save benwtks/b243adebb9154f9edc2725f72ce4071a to your computer and use it in GitHub Desktop.
Useful git commands

Useful git commands

Undo last unpushed commit without losing changes

git reset HEAD~1 --soft

Undo changes to a specific file

git checkout -- (file name)

Relevant git documentation page

Easily change commit message

git commit --amend -m "New commit message"

OR with the use of an alias in my .gitconig: git ca "New commit message"

Relevant git documentation page

Revert to a previous commit

git reset --hard (commit id)

Relevant git documentation page

Non-destructively revert changes

git revert (commit id)

to revert the last n commits,

git revert HEAD~n..master

Relevant documentation Atlassian doc

Unstage a file

git reset HEAD (file name)

OR with the use of an alias in my .gitconig: git unstage (file name)

Relevant git documentation page

Move a file without git thinking you've removed it and then created a new file that's unrelated to the deleted one

git mv <options>…​ <args>…​

Relevant git documentation page

Find commits that contained X in file Y

E.g. which commit removed this line? https://stackoverflow.com/questions/12591247/how-to-find-commit-when-line-was-deleted-removed

git log -c -S'missingtext' /path/to/file

Search diffs from git log for term

From https://stackoverflow.com/questions/2928584/how-to-grep-search-committed-code-in-the-git-history :

For this you can use -S and -G, which are subtly different...

The -S option essentially counts the number of times your search matches in a file before and after a commit. The commit is shown in the log if the before and after counts are different. This will not, for example, show commits where a line matching your search was moved.
With the -G option, the commit is shown in the log if your search matches any line that was added, removed, or changed.

For example,

diff --git a/test b/test index dddc242..60a8ba6 100644 --- a/test +++ b/test @@ -1 +1 @@ -hello hello +hello goodbye hello

Because the number of times "hello" appears in the file is the same before and after this commit, it will not match using -Shello. However, since there was a change to a line matching hello, the commit will be shown using -Ghello.

Useful stackoverflow questions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment