如何(从脚本)向 zsh 命令历史记录添加某些内容?
我希望能够查看我的命令历史记录并了解我发出各种命令的上下文 - 换句话说,“我在哪个目录中?”我可以通过多种方法来实现此目的,但所有这些(我能想到的)都需要操作 zsh 历史记录来添加(例如)带有 $(pwd) 结果的注释行。 (我可以创建名为 cd & Pushd & popd 等的函数,或者我可以使用 zsh 的 preexec() 函数以及它的 periodical() 函数最多每 X 秒添加注释行,就在我发出命令之前,或者也许还有其他方法。)
问题是,我不想直接操作历史文件并绕过 shell 的历史机制,但我无法找到一种方法(例如使用 fc 命令)来添加某些内容无需在命令行上实际输入即可查看历史记录。我怎么能这样做呢?
I'd like to be able to look through my command history and know the context from which I issued various commands--in other words, "what directory was I in?" There are various ways I could achieve this, but all of them (that I can think of) would require manipulating the zsh history to add (for instance) a commented line with the result of $(pwd). (I could create functions named cd & pushd & popd etc, or I could use zsh's preexec() function and maybe its periodic() function to add the comment line at most every X seconds, just before I issue a command, or perhaps there's some other way.)
The problem is, I don't want to directly manipulate the history file and bypass the shell's history mechanism, but I can't figure out a way (with the fc command, for instance) to add something to the history without actually typing it on the command line. How could I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
print -s
命令(请参阅man zshbuiltins
)将任何您想要的内容添加到历史记录中。您还可以创建一个名为zshaddhistory
的挂钩函数(请参阅man zshmisc
),该函数可以在创建历史内容时对其进行操作。请参阅我的 Bash 历史记录功能获取灵感。
You can use the
print -s
command (seeman zshbuiltins
) to add anything you want to the history. There's also a hook function you can create calledzshaddhistory
(seeman zshmisc
) that can manipulate history contents as they are created.See my Bash history logging functions for inspiration.