July 12, 2016

Erase last BASH command

enter image description here
Ever accidentally type your password on the commandline?
Want something better than editing the .bash_history file?
(Especially when you use cssh, parallel-ssh, psonsole or similar)
Below are some options:
#erase last command (least efficient)
history -d $(history | tail -n 2 | head -n 1 | awk '{print $1}')

#erase last command (more efficient)
history -d $(history | awk 'END{print $1-1}')

#erase last command and self (best)
history -d $(($HISTCMD-2)) && history -d $(($HISTCMD-1))

#ultimately add alias to .bashrc
alias eraselastcmd='history -d $(($HISTCMD-2)) && history -d $(($HISTCMD-1))'

#clear current session history
history -r

#don't save session history starting now
unset HISTFILE

#delete lines containing SOMETEXT from ~/.bash_history
 sed -i '/SOMETEXT/d' ~/.bash_history
Related options that can be set in ~/.bashrc
export HISTCONTROL=ignoreboth         # ignore duplicates and commands with " " (space-prefixed)
export HISTSIZE=                      # unlimited history
export HISTFILESIZE=                  # unlimited history
shopt -s histappend                   # append to history, don't overwrite it
export HISTIGNORE="ls:pwd:exit:date"  # do not record specified commands
-
good luck


Please consider crypto tipping: