How to Automate Saving Shell Commands Immediately After Execution Into History File

By default, the commands we execute are first temporarily stored into an internal memory and are written to our ~/.bash_history file only after we properly exit the shell session. Depending on our shell usage, this may cause some undesired results. For instance, if our connection to a remote host gets disconnected, our history file will not get updated and thus we will lose our previously executed commands. Furthermore, while our commands for one session are temporarily stored within system’s internal memory, we would not be able to access it from another shell session.

a) Configuring Bash

Open your ~/.bashrc file on your favorite text editor with appropriate privileges and add or edit the following line.
PROMPT_COMMAND="history -a"

b) Reloading Configuration

Load the modified configuration by sourcing the ~/.bashrc file.
source ~/.bashrc
And this automation will take effect immediately.


Documentation

Leave a Reply