CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingMedium
A junior administrator is learning Git and has accidentally committed a file containing sensitive information (e.g., a password) to the local repository. They have not yet pushed this commit to a remote server. Which of the following Git commands should be used to remove the sensitive file from the commit history before pushing to the remote repository?
- A`git reset --hard HEAD~1`
- B`git rm <sensitive_file> && git commit --amend --no-edit`
- C`git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch <sensitive_file>' --prune-empty --tag-name-filter cat -- --all`
- D`git revert HEAD`
Show answer & explanationAnswer & explanation
Correct answer: B. `git rm <sensitive_file> && git commit --amend --no-edit`
If the sensitive file was introduced in the most recent commit and has not been pushed, `git rm <sensitive_file>` followed by `git commit --amend --no-edit` will remove the file from the HEAD commit and rewrite that commit without creating a new history entry. This is the simplest and most appropriate solution for an unpushed, recent commit.
Why the other options are wrong
- A. `git reset --hard HEAD~1` would discard the entire last commit and its changes, including legitimate ones, which is too aggressive if only a file needs to be removed.
- C. `git filter-branch` is a powerful tool for rewriting history across multiple commits, but it is overkill and overly complex for removing a file from only the most recent, unpushed commit.
- D. `git revert HEAD` creates a new commit that undoes the changes of the last commit, leaving the sensitive file in the history of the original commit.
Removing Sensitive Files from Git History
Removing sensitive files from Git history, especially before pushing, is crucial for security. For recent, unpushed commits, amending the commit is the simplest method. For older or pushed commits, more drastic measures like `git filter-branch` or `BFG Repo-Cleaner` are needed.
- `git rm --cached <file>` removes file from index but keeps local copy.
- `git commit --amend` rewrites the most recent commit.
- Avoid `filter-branch` unless absolutely necessary due to complexity.
Memory trick: Amend to correct, Filter to rewrite.