Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to search all bash histories

Tags:

bash

If you have 10 xterms open, say, is it possible to search all the bash histories combined in some way?

I can do

history|grep something

on each one separately but I would sometimes like to avoid that.

like image 322
graffe Avatar asked Feb 08 '23 21:02

graffe


2 Answers

I am going to assume these xterm windows are all for the same userid, and are all on the same host. If they are not all the same user, then you must change their history file locations to use the same history file. If you need to do this, see this thread: https://superuser.com/questions/760830/how-do-i-change-the-bash-history-file-location

But the main problem you will have is that bash only writes its history to .bash_history when the shell is closed. However, you can edit your .bashrc to write the most recent command to .bash_history immeditately, like so:

# When the shell exits, append to the history file instead of overwriting i
shopt -s histappend

# After each command, append to the history file and reread it
export PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND$'\n'}history -a; history -c; history -r"

See this link for more info: https://unix.stackexchange.com/questions/1288/preserve-bash-history-in-multiple-terminal-windows

like image 191
R4F6 Avatar answered Feb 20 '23 09:02

R4F6


Bash has in-memory history and a history file ($HISTFILE, ~/.bash_history by default). By default, all your bash sessions share one history file which gets by the in-memory history of the last exiting bash shell whenever a bash shell exits.

You can change the behavior from overwriting to appending with:

shopt -s histappend

And you can manually invoke this dumping with

history -a #-a stands for append

What I do is I have history -a as part of my PROMPT_COMMAND so that each new prompt line adds a new record in the global history file.

Then, whenever I need the history from other sessions, I just load the global history file into the in-memory history with:

history -r

-r read the history file and append the contents to the history

The manual of the history command can be read with help history and more details regarding history are in man 1 bash.

Apart from setting shopt -s histappend and adding history -a to your PROMPT_COMMAND, it's also useful to set sizes (HISTFILESIZE, HISTSIZE) to some large values and HISTCONTROL, e.g. to "ignoreboth:erasedups" to eliminate duplicates.

Also, I find Ctrl-R to be a much more comfortable way of searching through history.

like image 22
PSkocik Avatar answered Feb 20 '23 09:02

PSkocik