undo your git changes

Have something in your code that you want to reverse but can’t remember the Git command? The below flowcharts cover the commands to use for common git situations. Diagrams generated using mermaid.

flowchart TD
    A(View code in previous commits) -- ...in the same branch --> B[git checkout <COMMIT-HASH>]
    A -- ...in a different branch --> C[git checkout <BRANCH>, git checkout <COMMIT-HASH>]
    A -- ... for specific file(s) --> D[git checkout <COMMIT-HASH> -- <FILE-PATH>]
flowchart TD
    A(Undo uncommitted changes in the current index) -- ...for all files --> B[git reset --hard]
    A -- ...for a specific file --> C[git checkout -- <FILE-PATH>]
flowchart TD
    A(Remove files from the staging area) -- ...for all files --> B[git reset]
    A -- ...for a specific file --> C[git reset <FILE-PATH>]
flowchart TD
    A(Undo the effects of one or more commits) -- ...by removing the commits from history --> B{keep changes in the current index?}
    B -- ...keep the changes in the current index --> C[...for the last N commits]
    C --> D[git reset --soft HEAD~N]
    B -- ...remove the changes in the current index --> E[...for the last N commits]
    E --> F[git reset --hard HEAD~N]
    A -- ...by creating new commits --> G{a specific commit or several commits?}
    G -- ...undo a specific commit --> H[git revert <COMMIT-HASH>]
    G -- ...several commits at once -->  I{from HEAD or between specific commits?}
    I -- ...from the HEAD --> J[git revert <GIT-HASH>^..HEAD]
    I -- ...between two specific commits --> K[git revert <OLDEST-COMMIT-HASH>..<NEWEST-COMMIT-HASH>]