Handy command for editing previously executed mistyped command and overwriting history entry with the fixed one

Solution 1:

This solution seems quite promising to me after I've been using it for a while.

Add the following to your ~/.bashrc file:

shopt -s histappend
PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"
fc_override_prev_command_if_no_args() {
        if [ $# -eq 0 ]; then
                fc
                history -d $(wc -l < ~/.bash_history)
                history -w
                history -c
                history -r
        else
                fc $@
        fi
}
alias fc=fc_override_prev_command_if_no_args

What this does is changing behaviour of the fc command when it is called with no arguments. When it is called with arguments, I made it to behave as it behaves usually, since otherwise its behaviour would be misleading without if/else/fi block, and without else part it wouldn't do anything at all.

On the other hand, when no arguments are provided, then fc command is executed, the last entry from the bash history is dropped and the cached history is reloaded from the file.

The part with reassignment of PROMPT_COMMAND variable I've borrowed from here and I found it useful as submitted commands are instantly available in bash histories of other currently-opened terminals with bash (OK, not really instantly, but even an action like sending SIGINT signal with Ctrl+C is enough to reload history cache).

Feel free to edit this answer or to comment if you find some parts of solution unnecessary.

Link to gist with the above snippet is available here