Simplify trace eraser with history -d approach

Changes:
- Replace complex awk/grep file manipulation with history -d
- Use in-memory history deletion instead of file parsing
- Delete entries in reverse order to maintain numbering
- Write cleaned history back to file with history -w

Benefits:
- Much simpler and more reliable
- Works with any HISTTIMEFORMAT configuration
- Native bash command handling (no awk complexity)
- Automatically handles timestamps correctly
- User-suggested improvement

Tested:
✓ Deletes 3 toolkit entries from 7-line test history
✓ Preserves normal commands
✓ Timestamps handled automatically by history -d
This commit is contained in:
cschantz
2025-11-10 23:16:37 -05:00
parent 74587a9ba5
commit 65b4a5e78b
+13 -35
View File
@@ -148,47 +148,25 @@ if [ "$CLEAN_HISTORY" = true ] && [ -f ~/.bash_history ]; then
# Disable history recording for this session to prevent re-adding commands
set +o history
# Build single grep pattern for efficiency (single-pass filtering)
# Clean in-memory history first using history -d (most reliable method)
echo " → Cleaning in-memory history..."
GREP_PATTERN="git\.mull\.lol|linux-server-management-toolkit|server-toolkit|launcher\.sh|erase-toolkit-traces"
# Backup and clean - handle HISTTIMEFORMAT timestamps
cp ~/.bash_history ~/.bash_history.bak.$$
# Get list of history entry numbers to delete (reverse order to maintain numbering)
entries_to_delete=$(history | grep -E "$GREP_PATTERN" | awk '{print $1}' | sort -rn)
entries_count=$(echo "$entries_to_delete" | grep -c '^' 2>/dev/null || echo 0)
# Use awk to remove matching lines AND their preceding timestamp lines
awk -v pattern="$GREP_PATTERN" '
/^#[0-9]+$/ {
# This is a timestamp line, store it
timestamp = $0
next
}
{
# This is a command line
if ($0 !~ pattern) {
# Keep this command - print timestamp (if exists) and command
if (timestamp != "") print timestamp
print $0
}
# Reset timestamp for next iteration
timestamp = ""
}
' ~/.bash_history.bak.$$ > ~/.bash_history.cleaned.$$ 2>/dev/null || true
# Delete each matching entry from in-memory history
for entry_num in $entries_to_delete; do
history -d "$entry_num" 2>/dev/null || true
done
# Calculate lines removed
lines_before=$(wc -l < ~/.bash_history.bak.$$ 2>/dev/null || echo 0)
lines_after=$(wc -l < ~/.bash_history.cleaned.$$ 2>/dev/null || echo 0)
lines_removed=$((lines_before - lines_after))
echo " ✓ Removed $entries_count toolkit-related entries from in-memory history"
# Replace history file with cleaned version
mv ~/.bash_history.cleaned.$$ ~/.bash_history
# Write cleaned in-memory history back to file
history -w
# Clean up backup
rm -f ~/.bash_history.bak.$$
echo " ✓ Removed $lines_removed toolkit-related history entries"
# Reload cleaned history into current session
history -c # Clear in-memory history
history -r # Reload from cleaned file
echo " ✓ Cleaned history written to file"
echo " ✓ In-memory history reloaded from cleaned file"
echo ""