2

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.

Kusalananda
  • 333,661
dawid
  • 201
  • 2
  • 7
  • https://superuser.com/questions/178801/bash-command-history-update-before-execution-of-command seems to be about the same wish, the solution suggested there is not straightforward though. – Henrik supports the community Mar 21 '24 at 16:09
  • You could simply echo the intended command and append it to the history file. Then call it back from history to edit/execute as you wish. – user9101329 Mar 21 '24 at 21:05

1 Answers1

1

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.

dawid
  • 201
  • 2
  • 7