Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I (from a script) add something to the zsh command history?

Tags:

shell

zsh

history

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?

like image 355
iconoclast Avatar asked May 12 '10 05:05

iconoclast


1 Answers

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.

like image 90
Dennis Williamson Avatar answered Oct 27 '22 18:10

Dennis Williamson