问题
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?
回答1:
You can use the print -s
command (see man zshbuiltins
) to add anything you want to the history. There's also a hook function you can create called zshaddhistory
(see man zshmisc
) that can manipulate history contents as they are created.
See my Bash history logging functions for inspiration.
来源:https://stackoverflow.com/questions/2816225/how-can-i-from-a-script-add-something-to-the-zsh-command-history