DEV Community

Cover image for 💾 Saving bash history across terminals
Ryan Collins
Ryan Collins

Posted on • Originally published at on

💾 Saving bash history across terminals

I’m very comfortable with bash, and I use it a lot with tmux. However, I didn’t like how I would lose command line history across these multiple terminals. After doing a little research, I figured out how to save my history for each terminal. Not only that, but I can also search all of the history. Now I don’t lose commands!

Setting up your .bashrc

Here are the relevant lines from my .bashrc. After adding them to yours, either log out and back in or include them into the current shell with source ~/.bashrc. No terminals will start saving their history unless you restart the shell or source the new lines.

# save history for multiple terminals
# create a folder to store the history
if [! -d "${HOME}/.bash_history_log"]; then
    mkdir "${HOME}/.bash_history_log"

# Add the tty to the history file
# Each terminal's history will be stored in 
# its own file
HISTSUFFIX=`tty | sed 's/\///g;s/^dev//g'`

# Time stamp for the history
HISTTIMEFORMAT="%y-%m-%d %H:%M:%S "

# don't put duplicate lines or lines starting with space in the history.

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)

# append to the history file, don't overwrite it
shopt -s histappend

# Add to the history everytime the prompt is shown
PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD/$HOME/~}\007";history -a'

# Search history
function searchhistory() {
    grep -ri "${1}" ~/.bash_history_log/*
alias shistory=searchhistory

Enter fullscreen mode Exit fullscreen mode

In practice

History is now automatically saved. To search for a command, I use the searchhistory function, which I alias to shistory. As an example, to see all of the Linux containers commands I have used, I can search the history with shistory lxc.

Since I modify the command prompt, you will probably want to change it to suit your personal needs. The secret sauce is the history -a which appends the commands to the history file that aren’t already added.


This is something I hacked together after a bunch of searches. Please let me know if it can be improved! Also, I post daily over at GozGeek if your interested in geeky stuff.

Top comments (0)