查看一系列 bash 历史记录

Sla*_*ast 51 bash command-history

history命令列出当前会话的所有历史记录。喜欢:

1 ls 
2 cd /root
3 mkdir something
4 cd something
5 touch afile
6 ls
7 cd ..
8 rm something/afile
9 cd ..
10 ls
11 history
Run Code Online (Sandbox Code Playgroud)

为了寻找感兴趣的项目,我可以管historygrep

history | grep ls
1 ls
6 ls
10 ls
Run Code Online (Sandbox Code Playgroud)

我还可以查看最后 3 个命令,例如:

history 3
11 history
12 history | grep ls
13 history 3
Run Code Online (Sandbox Code Playgroud)

但是我如何获得特定范围的历史?例如类似的东西:

history range 4 7
4 cd something
5 touch afile
6 ls
7 cd ..
Run Code Online (Sandbox Code Playgroud)

cuo*_*glm 82

代替history,您可以使用fc,它允许您选择范围:

fc -l 4 7
Run Code Online (Sandbox Code Playgroud)

  • 它甚至接受从末尾开始计数的负数,例如 `fc -l -16 -10`。 (7认同)
  • 嗯,想知道为什么我们需要一个全新的命令,而不仅仅是实际命令的参数...... (3认同)

小智 13

如果必须使用 history 命令,请通过 sed 或 awk 传送它:

history | sed -n '10,20p'

history | awk 'NR >= 10 && NR <= 20'
Run Code Online (Sandbox Code Playgroud)

否则 cuonglm 的答案是更好的选择。

  • 由于我们遇到了糟糕的替代方案,因此`head` 和`tail` 的组合将以一种更不优雅的方式解决这个问题。对于范围 10-&gt;25,您必须使用 `history | 头 25 | 尾 15`。 (6认同)
  • @questionto42standswithUkraine 老实说,我不相信 head+tail 比 `sed -n "${start},${end}p"` 有任何优势。如果您是,我邀请您添加答案。否则我会考虑添加一个但我不会承诺任何事情 (2认同)