How to make bash save a command to history at the moment a time-intensive command is issued, instead of only after the command ends or is killed?

There are many questions with similar wording regarding how to save commands before exiting the session which answer something else (PROMPT_COMMAND='history -a', histopt etc.).
This question has a misleading wording, for instance, but talks about not fully typed commands instead.

I am asking about an earlier trigger for bash auto-saving a command.
For example, I need to see from another terminal a history already including any command with unfinished execution.

I suspect bash implementation won’t be able to do that directly. However I think it worth asking.

Asked By: dawid


Following some ideias from the link mentioned by @Henrik in the comments section, putting this code at the end of .bashrc addressed my issue:

function saveafterenter {
   history -a
trap 'saveafterenter' DEBUG

Note: some people use history -c; history -r in addition to history -a; this doesn’t seem to be a good idea given the description in the man page. It will affect the living history of other sessions. We usually don’t want such a behavior. Each session is often more useful by branching the history in isolation until it is closed and its last command appended at the end of the history file. Intertwined sessions will alternate commands while appending to the file.

Answered By: dawid
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.