Skip to content

Instantly share code, notes, and snippets.

@fritz-c
Last active August 29, 2015 14:05
Show Gist options
  • Save fritz-c/2e83a7e5a3327ecb9ae4 to your computer and use it in GitHub Desktop.
Save fritz-c/2e83a7e5a3327ecb9ae4 to your computer and use it in GitHub Desktop.
Bash delete_last_n_histories function
# Delete the last n (default 1) histories from .bash_history and the history command cache
delete_last_n_histories() {
local count last HISTTIMEFORMAT regex temp
count=$((${1:-1} + 1))
last=$(($HISTCMD - $count))
echo "Deleting the following commands from .bash_history:"; history $count
HISTTIMEFORMAT="##%s###### "
# Contruct regex to find commands in .bash_history based on timestamp
# (NOTE: Change $(history $count) to $(history $(($count + 1))) if `history -a` is in $PROMPT_COMMAND)
while read line; do temp="${line#*#}"; regex="${temp%%##*}|$regex"; done <<< "$(history $count)"
# Omit selected histories from .bash_history
awk '/^('"${regex%|}"')$/ { del_mode = 1; next }
/^#[0-9]{1,11}$/ { del_mode = 0 } !del_mode { print }
' "$HOME/.bash_history" >| "$HOME/.history_delete_tmp" && mv "$HOME/.history_delete_tmp" "$HOME/.bash_history"
# Delete from cached history
for (( i=$(($HISTCMD)); i >= $last; i--)); do
history -d $i
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment