Super safe bash history

Intro

If you are like me, someone who spends a lot of time on the terminal, often ssh’d into a remote server, you start appreciating the power of scrolling through your bash history via Ctrl-r. It saves a ton of time from typing commonly used commands, quite the life saver.

Solution

Thinking about it, a simple idea came to me. Why not comment all the commands in bash history after each command execution?

function make_bash_history_safe() {
history -a # Save current history in memory to ~/.bash_history
history -c # Clear current history list in memory
# Comment all uncommented commands in ~/.bash_history with sed
sed -i -e 's/^\([^#]\)/# \1/g' ~/.bash_history
history -r # Reload history in memory from ~/.bash_history file
}
# Execute make_bash_history_safe after each command execution
PROMPT_COMMAND="make_bash_history_safe; "

Result

A screencast of safe history after each command execution
history -a; history -c; sed -i -e 's/^\([^#]\)/# \1/g'  ~/.bash_history ; history -r;

Slight Pitfall

With this, the bash history is now super safe. However, to execute any command from the history, you will now require to remove the comment character # from the beginning of line. This can get slightly frustrating, but it’s just matter of pressing:

<Ctrl-a> ; Go to beginning of line
<Ctrl-d> ; Delete first character on line, `#` in this case
<Return> ; Run the command
function remove_comment() {
READLINE_LINE=`echo ${READLINE_LINE} | sed -E -e "s/^[# ]+//g"`
}
bind -x '"\C-x\C-x": remove_comment'

Outro

Being server admins, we are bound to run commands which can have disastrous outcomes when run in wrong environment/directory at wrong time. However minuscule the possibility might be to execute a bad command from history, I personally would err on side of caution, eliminating it using good software-assisted workflows.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store