How to store all shell commands immediately after execution into .bash_history file

When using a bash shell all your entered commands are remembered by history library. The history library will keep track of every command you have entered. This is a default for most if not all Linux systems. However, the commands you enter are first temporarily stored into an internal memory and are written to your ~/.bash_history  only after you properly exit your shell session.

Depending on your shell usage this may cause some undesired results. For example, if your connection to a remote host gets disconnected, your history file will not get updated and thus you will lose all you previously entered commands. Furthermore, while your commands for one session are temporarily stored within system’s internal memory you would not be able to access it from another shell session.

Use the following linux command to force your shell to append every command entered during a current shell session into ~/.bash_history file:

shell 1: $ history -a

If you want your history to up updated and to reflect changes of your ~/.bash_history file you can read all history commands from ~/.bash_history file by:

shell 2: $ history -r

To make a modification to your bash shell and thus force it to automatically store every command into a ~/.bash_history file immediately after command execution you can enter a following line into your ~/.bashrc file:

declare PROMPT_COMMAND="history -a;history -r"

The above line will ensure that your history file gets appended with the latest executed command after every command execution history -a. It will also make sure that a content of your history file ~/.bash_history we be read and get available for any other for any already opened session by the same user. Please note that the last command executed within a one session will only by available for different session only after a command execution.



Comments and Discussions
Linux Forum