lsmsjg
Last Updated: April 28, 2017
·
131
· caleb531
Portrait v4

Bash: Function to remove last-typed command from history

I use Bash every day as my shell of choice. Because I tend to type quickly, I occasionally mistype a command and accidentally execute it before I can correct the typo, resulting in the mistyped command on my bash history (meaning I need to avoid in when pressing the up-arrow). Similarly, I might type a command which is syntactically-correct, but results in an error (and so the command might not be worth keeping in history)

So, I wrote a little Bash function to remove the very last command from the Bash history, which will take effect immediately. You can optionally remove the last n commands if you pass an integer argument. I call the function rmlastcmd.

Simply add the following to your .bashrc on Linux (or .bash_profile on macOS):

# Also be sure to add rmlastcmd to your HISTIGNORE;
# otherwise, rmlastcmd will always remove itself
export HISTIGNORE='rmlastcmd*'
# Remove last n commands from Bash history (n defaults to 1)
rmlastcmd() {
    local n="$([ -n "$1" ] && echo "$1" || echo 1)"
    local i
    for ((i=0; i<$n; i++)); do
        history -d "$((HISTCMD-1))"
    done
}

Running rmlastcmd is easiest if you have bash-completion installed and enabled, as you can simply type rml<tab>. Enjoy!

Say Thanks
Respond
Filed Under