Skip to content

Instantly share code, notes, and snippets.

@richhh7g
Last active March 9, 2024 03:13
Show Gist options
  • Save richhh7g/b3b677b589266e098dab28a8e5c8331e to your computer and use it in GitHub Desktop.
Save richhh7g/b3b677b589266e098dab28a8e5c8331e to your computer and use it in GitHub Desktop.
Shell - Erase logs 🤫
#!/bin/bash
if [ $# -lt 2 ]; then
echo "Usage: $0 <minutes_to_keep_logs> <commands_to_keep_in_history>"
exit 1
fi
logs_dir="/var/log"
minutes_to_keep_logs=$1
commands_to_keep_in_history=$2
delete_last_commands() {
local history_file="$1"
if [ -f "$history_file" ]; then
total_lines=$(wc -l < "$history_file")
lines_to_keep=$((total_lines - commands_to_keep_in_history))
sed -i "$lines_to_keep,\$d" "$history_file"
else
echo "$history_file not found."
fi
}
find "$logs_dir" -type f -mmin +$minutes_to_keep_logs -exec bash -c 'total_lines=$(wc -l < "$1"); lines_to_keep=$((total_lines - commands_to_keep_in_history)); sed -i "1,${lines_to_keep}d" "$1"' _ {} \;
delete_last_commands "$HOME/.bash_history"
delete_last_commands "$HOME/.ash_history"
delete_last_commands "$HOME/.zsh_history"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment