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

1

9

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?

Devisal answered 12/5, 2010 at 5:22 Comment(3)
Your directory changes go to that history - when you log in, you are at your $HOME - with a history file that is infinitely long, you can always parse the directory you were inLantz
Yes, thanks, but it can be a hassle. If I type cd /some/path/to/some/where then almost immediately type a command that would be okay. But in reality I'll have lots of cd .., popd, etc. commands, and the command I'm wondering about might in some cases be a hundred or more after the directory change. I'm looking for something that allows me to quickly and easily see where I was when I issued a command.Devisal
@Lantz Quite a narrow view of all the possible things that can happen through the course of a command line session. A script can drop you in a wholly different directory. Surely you dont suggest parsing such a script as well?Zap
C
13

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.

Chatav answered 12/5, 2010 at 7:34 Comment(4)
Is there a way to add it to the parent process' shell?Subirrigate
This doesn't work when I put it in a subshell: (print -s -- "# hi $(date)")Basir
@HappyFace: It adds it to the subshell's history. Try (print -s -- "# hi $(date)"; history) for a demonstration. You could use fc with appropriate options to save the history while in the subshell then read it back while in the parent shell.Chatav
@SridharSarnobat: See my comment to HappyFace.Chatav

© 2022 - 2024 — McMap. All rights reserved.