I usually have multiple bash sessions open. I want the history from multiple session to appear when doing a search (with Ctrl + R). When arrow keys are used only the current bash session's history should appear.

Many stackexchange questions relates to storing the history from multiple session. I already use it but my need is little different.

1 Answer 1


First off, there is not a clean solution to your problem without reimplementing some key component of how the shell (bash in this case) deals with history. Below is a solution that maintains your local history so that the arrows work as expected. Ctrl-r in turn is bound to searching your global history. The solution depends on an excellent utility for searching through your history called hh. Below are the instructions to set everything up.

Add to a startup file either ~/.profile,~/.bash_profile or ~/.bashrc:

# Whenever a command is executed, write it to a global history
export PROMPT_COMMAND="history -a ~/.bash_history.global"

# On C-r run the swap_history_reverse.sh script, 
bind -x '"\C-r": "~/swap_history_reverse.sh"'

Create the following script ~/swap_history_reverse.sh:

#! /usr/bin/env bash

# Point hh to global history
export HISTFILE=~/.bash_history.global

# Reverse search

# Restore local history
export HISTFILE=~/.bash_history 

Make the script executable:

chmod +x ~/swap_history_reverse.sh

Install hh, see INSTALL.

Once everything is in place, open up a new shell and give it a run.

You must log in to answer this question.

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