153 | | ==== Resetting to a previous commit ==== |
154 | | There are two types of resets soft and hard. |
155 | | A soft reset is done like this: |
156 | | {{{ |
157 | | git reset --soft HEAD@{N} |
158 | | }}} |
159 | | This resets your branch N previous commits (to a commit at a distance N from HEAD, the latest commit) but only in terms of git history. Hence your code remains untouched by git in a soft reset. |
160 | | |
161 | | A hard reset is done using: |
162 | | {{{ |
163 | | git reset --hard HEAD@{N} |
164 | | }}} |
165 | | This resets your branch N previous commits removing both history and changes to the file ever since. |
| 153 | ==== Undoing a commit ==== |
| 154 | You may need to remove a commit you've made, either if you find you don't want it, or if it needs to be fixed. (Note if your commit has already been pushed to !GitHub and accepted into the trunk, then you should use a new commit to take out unwanted changes. This section only applies if you're fixing up your repository before the changes are in trunk.) |
| 155 | |
| 156 | If you want to fix up your latest commit, you can undo the commit, and unstage the files in it, by doing: |
| 157 | {{{ |
| 158 | git reset HEAD~1 |
| 159 | }}} |
| 160 | This will return your repository to its state before the git add commands that staged the files. Your changes will be in your working directory. HEAD~1 refers to the commit below the current tip of the branch. |
| 161 | |
| 162 | If you want to uncommit N commits, but keep the code changes in your working directory: |
| 163 | {{{ |
| 164 | git reset HEAD~N |
| 165 | }}} |
| 166 | |
| 167 | If you want to get rid of your latest commit, and do not want to keep the code changes, you can do a "hard" reset. |
| 168 | {{{ |
| 169 | git reset --hard HEAD~1 |
| 170 | }}} |
| 171 | |
| 172 | Likewise, if you want to discard the last N commits, and do not want to keep the code changes: |
| 173 | {{{ |
| 174 | git reset --hard HEAD~N |
| 175 | }}} |
| 176 | |
| 177 | If you are not entirely sure you want to discard the code changes, but need a branch without them, you can simply check out a new branch that ends at the last commit you want. E.g. to make a branch that ends N commits before the latest: |
| 178 | {{{ |
| 179 | git checkout -b <new_branch_name> HEAD~N |
| 180 | }}} |
| 181 | See below for more on using multiple branches. |