Linux 学习记录:history 查看历史命令列表

history 命令能够查询到我们之前在 bash 里面输入的指令历史,这些指令一般存放在 HOME 目录下的 .bash_history 文件里,这个文件里面存放多少条指令记录,与环境变量 $HISTSIZE 有关,一般在 Ubuntu 等发行版中,这个值是 1000

history 命令的工作方式是这样的:当我们登录到 Linux 主机后,bash 首先会读取 .bash_history 文件,将里面的存放的所有命令历史(一般为 1000 条)读入到内存当中,这样,我们就能输入 history 查看这次登录以前所输入的所有命令。

我们在本次登录下所输入的所有命令,在我们退出之前是不会被写入到 .bash_history 文件的,也就是说,只有我们推出本次登录,这次登录里所输入的所有指令才会被写入到该文件。在我们没退出登录之前,.bash_history 文件的内容是不会变动的。

但是,我们在登录过程中所输入的所有指令,使用 history 命令是能够查看到的,因为这些命令都存在内存当中,而不是从文件中读取到的。

下面举个例子具体说明下。

首先,我们登录到 Linux,查看 .bash_history 最后 5 条记录(对应最近的 5 条指令):

1
cat ~/.bash_history | tail -n 5

输出:

1
2
3
4
5
6
tan@tjt1024:/mnt/c/Users/tanjuntao$ cat ~/.bash_history | tail -n 5
vim man_db.conf
echo $HISTSIZW
echo $HISTSIZe
echo $HISTSIZE
exit

接着,我们使用 history 命令来查看最近 5 条记录:

1
2
3
4
5
6
tan@tjt1024:/mnt/c/Users/tanjuntao$ history 5
1058 echo $HISTSIZe
1059 echo $HISTSIZE
1060 exit
1061 cat ~/.bash_history | tail -n 5
1062 history 5

可以看到,在 .bash_history 文件的基础上,此次登录后,我们输入了两条新命令:

  1. cat ~/.bash_history | tail -n 5
  2. history 5

这两条命令马上就能被 history 捕捉到,因为 history 是从内存中读取指令历史。

我们再看看此时 .bash_history 的内容,如下:

1
2
3
4
5
6
tan@tjt1024:/mnt/c/Users/tanjuntao$ cat ~/.bash_history | tail -n 5
vim man_db.conf
echo $HISTSIZW
echo $HISTSIZe
echo $HISTSIZE
exit

还是和之前一样的,说明本次登录后,输入的所有命令都没有被记录到该文件中。

接着我们输入 exit 退出登录,再重新登录,再来查看 .bash_history 的内容,发现变成这样:

1
2
3
4
5
6
tan@tjt1024:/mnt/c/Users/tanjuntao$ cat ~/.bash_history | tail -n 5
exit
cat ~/.bash_history | tail -n 5
history 5
cat ~/.bash_history | tail -n 5
exit

说明上次登录过程中输入的所有指令,已经被写入到 .bash_history 文件中了。

如果我们想让登录过程中输入的所有指令都写入到 .bash_history 中,而不是必须要退出当前登录,我们可以使用 history 命令的 -w 参数:

1
history -w

接着上面的例子,我们重新登录后查看了 .bash_history 的最后 5 条记录。接下来,我们输入 history -w,再来查看该文件内容:

1
2
3
4
5
6
tan@tjt1024:/mnt/c/Users/tanjuntao$ cat ~/.bash_history | tail -n 5
history 5
cat ~/.bash_history | tail -n 5
exit
cat ~/.bash_history | tail -n 5
history -w

说明 history- w 将该命令自己,已经该命令前面的所有命令都写入到 .bash_history 中了,但是我们最近一条查看 .bash_historycat ~/.bash_history | tail -n 5 并没有被写入。

Donate comment here