Bash – Sticky entries in shell history

bashcommand historyshellzsh

Is there a way one could make some commands "sticky" in a shell history?

I want to save some favourite commands that would be searchable with Ctrl+R, like the rest of the history, but they should never expire.

Best Answer

A simple way is to put code in your shell startup file to read an additional history file, and make sure that you store sufficiently many history lines in memory so that the sticky lines aren't forgotten.

bash

In ~/.bashrc:

history -r ~/.bash_history.sticky

Also make sure that HISTSIZE is at least HISTFILESIZE plus the number of lines in ~/.bash_history.sticky plus the number of commands you execute in a long session, e.g.

HISTFILESIZE=1000
HISTSIZE=10000

If you want to ensure that the sticky history entries remain in memory without having a very large HISTSIZE, you can do it by manually trimming the history in PROMPT_COMMAND with history -d, but it's difficult to get right if you have erasedups in HISTCONTROL.

zsh

In ~/.zshrc:

fc -RI ~/.zsh_history.sticky

Also make sure that HISTSIZE is at least SAVEHIST plus the number of lines in ~/.zsh_history.sticky plus the number of commands you execute in a long session, e.g.

SAVEHIST=1000
HISTSIZE=10000

If you want to ensure that the sticky history entries remain in memory without having a very large HISTSIZE, you can do it by manually trimming the history in precmd, but it's cumbersome (zsh doesn't really support rewriting history, you have to fc -W into a temporary file and read back an edited version) and difficult to get right if you have the hist_ignore_dups or hist_ignore_all_dups option set.

Related Question