brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: shopt -s histappend with history -a keeps bash history from every terminal

Bash
~/tips/tip-bash-histappend-history-a

shopt -s histappend

Saves every command from every open terminal to your bash history instead of only the last one.

Open three terminals, work in all of them, close them, and bash history only remembers what happened in the last one you closed. I think that default is a bit mean, because it quietly throws away commands you might want back next week.

The cause: when an interactive bash exits, it writes its history list to ~/.bash_history and overwrites the file. The last shell to exit wins. Two lines in ~/.bashrc change that:

shopt -s histappend
PROMPT_COMMAND="history -a${PROMPT_COMMAND:+; $PROMPT_COMMAND}"

histappend makes bash append to the history file on exit instead of overwriting it. history -a appends the lines you typed since the last save, and putting it in PROMPT_COMMAND runs it right before every prompt. So each command lands in the file the moment it finishes, even if the terminal later crashes or gets closed with the window’s X button. The ${PROMPT_COMMAND:+...} part keeps whatever your distro already had in there.

Here is what that looks like in practice. Run a long rsync in one terminal, open a fresh terminal later and press the Up arrow: the rsync line is there.

The caveat is that already open terminals do not pick up each other’s commands by themselves. Each shell loads the file when it starts. If you want the lines from other terminals in the shell you are in, run history -n, which reads the lines that were added to the file since this session started. I wouldn’t put that in PROMPT_COMMAND as well: then the Up arrow suddenly shows commands from another window, which I find more confusing than useful.

Further reading: Bash history facilities (GNU Bash manual), Bash history builtins (GNU Bash manual)

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link