Practical Examples of Git Un-add
Removing a Single File from the Staging Area
Suppose you've accidentally git add
-ed a file that you don't want to commit. You can use git reset
to remove it from the staging area:
## Add a file accidentally
git add sensitive_file.txt
## Remove the file from the staging area
git reset sensitive_file.txt
After running the git reset
command, the sensitive_file.txt
will be removed from the staging area, but it will still be present in your working directory.
Unstaging All Changes
If you've git add
-ed multiple files and want to remove them all from the staging area, you can use git reset
without any file paths to unstage all changes:
## Add multiple files
git add *.txt
git add *.py
## Unstage all changes
git reset
This will remove all the changes from the staging area, but they will still be present in your working directory.
Undoing the Last git add
If you've git add
-ed some changes and want to undo the last git add
, you can use git reset HEAD~1
to move the branch pointer back one commit and remove the changes from the staging area:
## Add some changes
git add file1.txt file2.txt
## Undo the last git add
git reset HEAD~1
After running this command, the changes in file1.txt
and file2.txt
will be removed from the staging area, but they will still be present in your working directory.
Discarding Local Changes
If you've made some local changes and want to discard them completely, you can use git reset --hard
to reset the working directory to the last committed state:
## Make some local changes
echo "new content" >> file.txt
## Discard all local changes
git reset --hard
This will discard all the local changes in your working directory and reset it to the last committed state.
Remember, the --hard
option should be used with caution, as it will permanently discard any local changes in your working directory.