Strovent SystemsSign in
Reference

Bash history lost or missing commands after SSH disconnect, tmux or several terminals

Bash keeps history in memory and writes ~/.bash_history only at exit, overwriting it. Use histappend and history -a so each command is saved at once.

Commands you typed yesterday are missing from history or from ~/.bash_history, or only the commands from one of your windows survived. This is how bash saves history by default.

How bash saves history

  • While the shell runs, history lives in memory only.
  • When the shell exits, bash writes its last HISTSIZE commands to the history file (HISTFILE, by default ~/.bash_history).
  • Unless the histappend option is set, that write overwrites the file. Then bash trims the file to HISTFILESIZE lines.
  • A new shell reads the file once, when it starts. It does not see commands typed in other shells after that.

From this, the usual losses follow:

  • Several shells at once (tmux windows, tabs, two SSH sessions): without histappend, the last shell to exit overwrites the file with only its own commands.
  • The shell was killed instead of exiting. A shell that gets kill -9, or is killed when memory runs out, never writes its history. A dropped SSH connection normally sends the shell a hangup signal, and bash still saves on the way out, but not if it is killed before that.
  • The history is too short. HISTSIZE defaults to 500 commands, and HISTFILESIZE defaults to the same value.
  • Nothing is saved at all: HISTFILE is unset or empty, or your account cannot write to the file.

Fix: append, and save after each command

Add this to ~/.bashrc:

shopt -s histappend
PROMPT_COMMAND="history -a${PROMPT_COMMAND:+; $PROMPT_COMMAND}"
HISTSIZE=10000
HISTFILESIZE=20000
  • shopt -s histappend makes the exit write append instead of overwrite. Some distributions, Debian for one, already set it in the default .bashrc.
  • history -a appends the commands typed since the last save. Run from PROMPT_COMMAND, it saves each command before the next prompt, so a killed shell or a dropped connection loses nothing.
  • The larger sizes keep more history. Pick any numbers you like.

Open a new shell, or run source ~/.bashrc, for the change to apply.

Share history between open shells

Commands saved by one shell are not loaded into others that are already running. To pull them in by hand, run history -n, which reads lines added to the file since the shell started. Adding history -n to PROMPT_COMMAND after history -a does this at every prompt, but then the Up arrow mixes commands from all windows.

Sources

Spotted a mistake? Email [email protected].