归档

linux下多个终端命令历史记录保存

在此之前我一直以为linux下使用screen 或者tmux,等终端复用工具的话,命令历史是不会保存的。

可是事实是会保存到~/.bash_history 文件中去,只是历史记录并不是实时保存,只有在当前(session1)回话结束之后(执行了exit命令后) bash才会把历史记录写入到.bash_history文件中。即使已经写入到了.bash_history中,假如某个回话(session2)在写入之前就已经开启了,那么这个回话(session2)中的历史记录并不会实时刷新,也就是说你执行一遍history 打印出来的命令并没有 (session1)中的历史命令

做个测试

首先新建两个回话

root@local:~# screen -S session2
[detached from 21165.session2]
root@local:~# screen -S session1
[detached from 21178.session1]
root@local:~# screen -list
There are screens on:
        21178.session1  (06/07/2013 01:59:18 PM)        (Detached)
        21165.session2  (06/07/2013 01:59:09 PM)        (Detached)
2 Sockets in /var/run/screen/S-root.

进入session1

root@local:~# screen -r session1
root@local:~# history 10
 1992  ls s13
 1993  exit
 1994  ls s21
 1995  exit
 1996  tail -f .bash_history
 1997  exit
 1998  ls
 1999  tail -f .bash_history
 2000  exit
 2001  history 10
root@local:~# ls s6767
ls: cannot access s6767: No such file or directory

在进入session2

 1999  tail -f .bash_history
 2000  exit
 2001  history
root@local:~# history 10
 1993  exit
 1994  ls s21
 1995  exit
 1996  tail -f .bash_history
 1997  exit
 1998  ls
 1999  tail -f .bash_history
 2000  exit
 2001  history
 2002  history 10

执行history 从第2001 行开始 都是不一样的

再次进入session1 并退出 新建session3 执行history命令(由于history记录数的限制,只能存储2000条历史记录,所以行数发生了变化)第1999行为在session1中执行的命令

 1997  exit
 1998  history 10
 1999  ls s6767
 2000  exit
 2001  history

进入session2(可以看到没有发生变化)

root@local:~# history 15
 1989  ls b2
 1990  exit
 1991  ls s12
 1992  ls s13
 1993  exit
 1994  ls s21
 1995  exit
 1996  tail -f .bash_history
 1997  exit
 1998  ls
 1999  tail -f .bash_history
 2000  exit
 2001  history
 2002  history 10
 2003  history 15

 若想多个回话之间实时共享历史记录,可以试试下面这种方法

~/.bashrc 或 ~/.bash_profile 文件中:
shopt -s histappend
PROMPT_COMMAND=’history -a’

 

这个是在网上搜到的,我没试因为我觉得还是分开的好些 一般建立多个回话是有多个任务要进行
要是历史记录共享的话就有些乱了