Bash 如何从一个非交互式shell中查看历史记录的输出,该shell给出了HISTFILE的路径?

Bash 如何从一个非交互式shell中查看历史记录的输出,该shell给出了HISTFILE的路径?,bash,emacs,sh,Bash,Emacs,Sh,在emacs中,我想使用shell命令来字符串,基本上检索类似history | tail-n5的内容。问题是history是内置的bash(仅在交互模式下?),所以它不起作用。由于我只对修饰输出的只读快照感兴趣,是否有办法解析历史文件的内容(假设它是~/.bash_history),并像historybash命令那样输出行号和日期 换句话说,有没有一种方法可以做到: (shell命令字符串“history--pretty dump to stdout with date time linenu

在emacs中,我想使用
shell命令来字符串
,基本上检索类似
history | tail-n5的内容。问题是
history
是内置的bash(仅在交互模式下?),所以它不起作用。由于我只对修饰输出的只读快照感兴趣,是否有办法解析历史文件的内容(假设它是
~/.bash_history
),并像
history
bash命令那样输出行号和日期

换句话说,有没有一种方法可以做到:

(shell命令字符串“history--pretty dump to stdout with date time linenum--filename~/.bash_history”)

??(或者,可能是另一种解决方法?

使
历史记录
命令输出一些东西 我预计
set-o history
会失败,因为它将使用历史文件
$HISTFILE
,对于非交互式shell,它很可能是未设置的。假设历史记录存储在
~/.bash\u history
中,则可以执行

HISTFILE=~/.bash_history; set -o history; history | tail -n5
$ myCommand
$ emacs # and inside emacs the shell command `history` as shown above
但是,这将通过添加
history | tail-n5
来修改您的历史记录。更好的方法是在不启用历史记录的情况下读取历史记录文件:

history -r ~/.bash_history; history | tail -n5
当前会话中的命令 假设您在交互式终端会话中并执行

HISTFILE=~/.bash_history; set -o history; history | tail -n5
$ myCommand
$ emacs # and inside emacs the shell command `history` as shown above
。。。那么您很可能不会在历史记录中看到
myCommand
。这是因为bash仅在关闭会话时将历史记录写入历史记录文件。您可以使用
history-a
手动更新历史文件,因此以下操作应该有效:

$ myCommand
$ history -a
$ emacs # and inside emacs the shell command `history` as shown above
由于大多数人通常会忘记
history-a
,因此最好在
.bashrc
中自动执行此步骤,无论是在每个提示符下(
prompt\u COMMAND=“history-a
),还是仅在emacs上(
emacs(){history-a;COMMAND emacs”$@“}

漂亮的印刷品 有没有一种方法可以像[…]
——使用date-time-linenum将数据转储到标准输出


history
命令的历史记录格式由
HISTTIMEFORMAT
控制。在调用
emacs

内部的
history
之前,必须设置并导出该格式。如果shell不是交互式的,则必须打开历史记录:
set-o history
。如果您还希望历史记录替换工作,则可以通过
set-H
启用它,但在我看来,这在脚本中有些毫无意义。Socowi,谢谢你!我最终从emacs中起草了整个命令:
HISTFILE=/path/to/HISTFILE;HISTTIMEFORMAT='%Y%m%d%T';history-r$HISTFILE;history | tail-n5
唯一的缺点是它重新定义了HISTTIMEFORMAT b但我认为这样做的好处是在emacs包中进行控制,其offset将包含实际命令:)