Multiple bash sessions and their history

I’ve trying to move some console work to my mobile device, iPhone, especially.
So I start to use Blink Shell, which is an iOS app supports ssh and mosh connection.

Then, naturally I bump in to the problem when there is more than one bash session undergoing, the bash command history gets mess up.

If you ever use !numbers, eg. !1, run the first command in bash history, this situation gets annoying at some point.

To manipulate bash history, we need these settings:

1
2
3
4
5
6
7
# Append command history to .bash_history
shopt -s histappend

# Actions to manage .bash_history while in a session
history -a # Append the history
history -c # Clear the history
history -r # Load the history

And here is what I want:

  • every new bash session loads all previous history
  • existing session save commands after each enter hits

This is what I put into ~/.bashrc (in Ubuntu Linux, you may also put into .bash_profile, but eventually .bashrc will gets loaded)

1
export PROMPT_COMMAND="history -a; history -r; $PROMPT_COMMAND"

Archiving bash_history

Also, I found this idea [0] to archive your history once in a while.
Simply added following into my bashrc:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Keep=768
History=~/.bash_history
Archive=~/.bash_history_archive
# Backup="$Archive/bash_history.$(date +%Y-week-%V)"

Backup="$Archive/bash_history.$(date +%Y-%m-%d)"

if [ "$History" -nt "$Backup" ]; then
# history file is newer then backup
if [ -f $Backup ]; then
# there is already a backup
cp -f $History $Backup
else
echo "History move into Archive"
# create new backup, leave last few commands and reinitialize
mv -f $History $Backup
tail -n$Keep $Backup > $History
fi
fi

On a final thought, it would be interesting if I can keep all the commands I typed and analyzing later in my life.