<分区>
我希望能够查看我的命令历史记录(一直回到用户的开头)。
是否可以保证文件 .bash_history 将继续被附加到?
如果文件开始被截断的位置存在限制(希望从头开始截断),是否有办法消除该限制?
<分区>
我希望能够查看我的命令历史记录(一直回到用户的开头)。
是否可以保证文件 .bash_history 将继续被附加到?
如果文件开始被截断的位置存在限制(希望从头开始截断),是否有办法消除该限制?
最佳答案
有许多环境变量可以控制历史记录在 Bash 中的工作方式。 bash 联机帮助页的相关摘录如下:
HISTCONTROL
A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ignorespace, lines which
begin with a space character are not saved in the history list. A value of ignoredups causes lines matching the previous history entry to not be
saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A value of erasedups causes all previous lines matching the current
line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does
not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE. The second and
subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL.
HISTFILE
The name of the file in which command history is saved (see HISTORY below). The default value is ~/.bash_history. If unset, the command history
is not saved when an interactive shell exits.
HISTFILESIZE
The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, by
removing the oldest entries, to contain no more than that number of lines. The default value is 500. The history file is also truncated to this
size after writing it when an interactive shell exits.
HISTIGNORE
A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the begin-
ning of the line and must match the complete line (no implicit `*' is appended). Each pattern is tested against the line after the checks speci-
fied by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, `&' matches the previous history line. `&' may be
escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command
are not tested, and are added to the history regardless of the value of HISTIGNORE.
HISTSIZE
The number of commands to remember in the command history (see HISTORY below). The default value is 500.
直接回答您的问题:
不,不能保证,因为可以禁用历史记录,一些命令可能不会被存储(例如,以空格开头)并且可能会对历史记录大小施加限制。
至于历史大小限制:如果取消设置 HISTSIZE
和 HISTFILESIZE
:
unset HISTSIZE
unset HISTFILESIZE
您将防止 shell 截断您的历史文件。但是,如果您有一个运行的 shell 实例设置了这两个变量,它会在退出时截断您的历史记录,因此解决方案非常脆弱。如果您绝对必须维护长期的 shell 历史记录,则不应依赖 shell 并定期将文件复制(例如,使用 cron 作业)到安全位置。
如 man page 中所述,历史截断总是首先删除最旧的条目以上摘录。
关于linux - 文件 ".bash_history"是否总是记录我发出的每条命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8168676/