6.1. Deleting Data - shinokada/gitnotes GitHub Wiki

Deleting data

Deleting working directory

Show information about files in the index and the working tree

git ls-files

Remove a file

git rm file-name

This is the same as git add .

Undoing unstaged changes

checkout

// target one file
git checkout file-name
// targe all files
git checkout .

restore

// target one file
git restore file-name
// target all files
git restore .

Cleaning an unstaged file.

touch file-to-be-removed
// it is not in the index and the working tree
git clean -dn
git clean -df
  • -d delete untracked one.
  • -n list before deleting.
  • -f force without asking further questions.

Undoing staged changes

git checkout won't work after running git add. Use git reset for staged files.

git add file-name
// old way
git reset file-name // this move the file-name to unstaged area
git checkout file-name  // now you can use checkout

git store

git add file-name
git restore --staged file-name
git checkout file-name

Deleting commits with git reset

// show the staging area
git ls-files
// soft
git add file-name
git commit -a "file-name added"
git reset --soft HEAD~1 // remove the latest commit and the file-name is still available but it remains the staging area
git commit -m "again add file-name"
// default
git rest HEAD~1 // remove the latest commit and the file-name is still available from the staging area
git add file-name // since it is not on the staging area, you need to add
git commit -m "again add file-name"
// hard
git reset --hard HEAD~1  // remove the latest commit, the changes from the working direcotry, and removing the changes from the staging area

Deleting branches

// show all branches
git branch
git branch -d  branch-name-one branch-name-two // if you merge these branhes, use -d
git branch -D  branch-name-one branch-name-two // if you merge it or not it forces to delete, use -D

Committing detached HEAD

Changes in a detached HEAD will be lost.

git checkout some-commit-hash
// check branch
git branch
// this will show main/master and (HEAD detached at some-hash)
// add a change
git add .
git commit -m "change message"

// method 1
// you can create a branch here too
git branch branch-name-two

// method 2
git switch master
// you need to create a new branch with the previous some-commit-hash
git branch branch-name some-commit-hash
git switch branch-name
// check the changes
git swich master
git merge branch-name

Understanding .gitignore

*.log
!test.log // use ! to not be ignored
web-app/*
⚠️ **GitHub.com Fallback** ⚠️