第 182 / 187 篇

17.11. 命令历史

说明

本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/Appendix2/history.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。

17.11. Command History

history 命令列出 shell 最近运行过的命令的历史。有时候,用户查看过去运行过的命令会很有用。例如,记起自己给某个程序用过的具体命令行参数。它还允许用户用一种特殊的简写记法,从 shell 的历史中重新执行某条特定的命令。

The history command lists the recent history of commands that have been run by the shell. Sometimes it can be useful for a user to see commands that have been run in the past. For example, to remember the specific command line arguments they used to a program. It also allows a user to re-execute commands with a special shorthand notation to re-run a specific command from the shell’s history.

下面是运行 history 命令的一个例子:

Here is an example run of the history command:

1
2
3
4
5
6
7
8
9
10
$ history
35 8:17 ls
36 8:17 cd classes/CS31
37 8:17 echo "hi Sam"
38 8:17 ./a.out infile.txt outfile.txt &
39 8:18 ./a.out &
40 8:18 ps
41 8:18 pkill a.out
42 8:18 ps
43 8:18 history

这个例子展示了 shell 最近历史中运行过的一系列命令。历史中的每条命令都带有一个数字,表示它在历史中的位置,以及该命令开始运行的时间。最近运行的命令是第 43 条命令 history。要重新运行历史中的某条命令,可以用 ! 后跟命令的编号,而 !! 重新运行最近的上一条命令。对于带有一长串命令行参数的命令,这特别便于重新运行。例如,要重新运行历史中的第 37 条命令(echo "hi Sam"),用户只需在 shell 提示符下输入 !37:

This example shows a series of a few commands run in the shell’s recent history. With each command in the history is a number indicating its position in the history and the time the command was started. The most recently run command was the 43nd command, history. To re-run a command from the history, you can use ! followed by the number of the command, and !! runs the most recent previous command again. This is particularly useful for easily re-running commands that have a long list of command line arguments. For example, to re-run command 37 from the history (echo "hi Sam"), a user just needs to type !37 at the shell prompt:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ !37
hi Sam
$ history
35 8:17 ls
36 8:17 cd classes/CS31
37 8:17 echo "hi Sam"
38 8:17 ./a.out infile.txt outfile.txt &
39 8:18 ./a.out &
40 8:18 ps
41 8:18 pkill a.out
42 8:18 ps
43 8:18 history
44 8:20 echo "hi Sam"
45 8:20 history

注意,!37 本身不会出现在历史中,而历史中的第 44 条命令列出的命令行与第 37 条命令行相同,也就是通过输入 37! 重新运行的那一条。

Note that !37 does not show up in the history, but that command number 44 from the history lists the same command line as command line 37, the one that was re-run by entering 37!.

译注

「37!」是笔误,应为上文所说的 !37。

17.11.1. 参考资料

17.11.1. References

更多信息参见:

For more information see:

  • history 的手册页:man history
  • The history man page: man history