In my .bashrc I have already added:

# https://stackoverflow.com/a/40158199/9881330
function rescue_history {
    history -a
trap rescue_history SIGHUP

However, this does not work, because after client_loop: send disconnect: Connection reset by peer the history is still lost. Which is very annoying since the useful entered commands are all lost!

The core question: How to configure .bashrc to save the history when ssh connection is reset by peer?

Very confused that this "history saving" behavior is not enabled by default.

My .bashrc also has also this (if it might help):

# new history settings
# http://jesrui.sdf-eu.org/remember-all-your-bash-history-forever.html
#HISTIGNORE=?:??      # lines with one or two characters are discarded from the history (e.g. ls commands)
shopt -s histappend  # append to history, don't overwrite it
# attempt to save all lines of a multiple-line command in the same history entry
shopt -s cmdhist
# save multi-line commands to the history with embedded newlines
shopt -s lithist
  • 1
    You can modify PROMPT_COMMAND to save history after each command instead storing it in the memory and dumping it to the file when exiting which is the default behavior. Dec 9, 2020 at 21:05
  • Question asks for Bash, but for those with zsh this is trivial to do. See unix.stackexchange.com/questions/389881/… Dec 22, 2022 at 5:53

1 Answer 1


You can use the PROMPT_COMMAND special variable to run history -a every time you enter a command.


This will mix up commands from concurrent sessions which might make for a confusing scrollback.

To overcome that, here's a slightly more complicated version, which should create a time, tty and pid stamped file in your home directory, per session.

SESSION_HISTORY_FILE="${HOME}/bash_history_$(date -d "$(ps -olstart= -p$$ | awk '{print $2,$3,$5,$4}')" +%F_%H-%M-%S)$(tty | tr / _)_$$"

The idea here being to create a properly contexted record of commands issued.

You wouldn't see these in scroll back for a terminated session (unless you added a ;history -a).

  • Any idea on why trap rescue_history SIGHUP does not work in my case? Meaning that since bash will (usually) receive a SIGHUP on disconnect (stackoverflow.com/a/40158199/9881330), it seems that in my case bash does not receive SIGHUP on disconnect. But why? Both sh --version and bash --version give GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu).
    – pmor
    Dec 11, 2020 at 10:39
  • 1
    I'm speculating, but I'd surmise that it's not receiving something as graceful as a HUP, more like a KILL.
    – bxm
    Dec 11, 2020 at 15:47
  • Issue is found with this code: unix.stackexchange.com/questions/626303/….
    – pmor
    Dec 27, 2020 at 12:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .