Account imageLoginSign UpAccount image
Loading votes....
Save Question

How to undo the last commit in Git but keep the changes in my working directory?

clock icon

asked 3 months ago

Message icon

1

Eye icon

5

I committed too early:

1git commit -m "WIP"
1git commit -m "WIP"

I want to "uncommit" so I can add more files or edit the commit message. I don't want to lose my changes. git reset --hard sounds scary – what's the safe way?

1 Answer

Undoing the Last Commit in Git

To undo the last commit in Git while keeping the changes in your working directory, you can use the git reset command with the --soft option.

Why git reset --soft?

The --soft option will undo the last commit, but it will keep your changes in the staging area. This means you won't lose any of your work.

Step-by-Step Solution

Here's how you can do it:

1git reset --soft HEAD~1
1git reset --soft HEAD~1

This command will:

  • Undo the last commit
  • Keep your changes in the staging area
  • Allow you to add more files or edit the commit message

Alternative Solution

Alternatively, you can also use git reset --soft HEAD^ to achieve the same result.

What to Do Next

After running the git reset --soft command, you can:

  • Add more files to the staging area using git add
  • Edit the commit message using git commit --amend
  • Commit your changes again using git commit

Remember to replace HEAD~1 or HEAD^ with the actual commit hash if you want to undo a specific commit that's not the most recent one.

Example Use Case

Let's say you committed too early with the message "WIP" and you want to add more files to the commit:

1git commit -m "WIP"
2git reset --soft HEAD~1
3git add more_files.txt
4git commit -m "Updated commit message"
1git commit -m "WIP"
2git reset --soft HEAD~1
3git add more_files.txt
4git commit -m "Updated commit message"

By using git reset --soft, you can safely undo the last commit and keep your changes in the working directory.

1

Write your answer here

Top Questions