Put a command in history without executing it

In bash, if I have a command on the line, and I press Alt-# (with the cursor anywhere on the line), it adds a # to the front of the line, commenting it out, 'executes' it (which does nothing since it's now commented out), and puts it into the history. It's really useful for when I type some or all of a command and realise I need to run another command first and come back to that one later.

How can I do the same operation in zsh? The commenting-out isn't important: all I care about is that the command doesn't happen right now, but can be retrieved from history later.


Three options:

  • zsh has the keyboard shortcut Alt + Q by default that pushes the current line.

    Use it like this:

    1. Type command.

    2. Press Alt + Q.

    3. Execute othercommand.

    4. command will reappear.

    Technically, this doesn't put it in the history. Also, if you need to execute another command before command, you have to press Alt + Q again.

  • Also by default, the keyboard shortcuts Ctrl + U and Ctrl + Y cut and yank (paste) the current line.

    Use them like this:

    1. Type command.

    2. Press Ctrl + U.

    3. Execute othercommand.

    4. Press Ctrl + Y.

    5. command will reappear.

    This would work in bash as well and it uses its own clipboard, i.e., they contents of the clipboard managed by Ctrl + (Shift +) C / V and select / middle-click will remain unaltered.

  • Last but not least, you can permanently enable comments on the command-line by executing

    echo setopt interactivecomments >> ~/.zshrc
    

    Alt + # doesn't work here, but Ctrl + A / Home, #, Enter achieves the same result.

To see all available keyboard shortcuts, execute

bindkey

Option four (as an answer to the title of the question, not its explanation ;-):

  • print -S "this line goes to the history"

Excerpt from zshbuiltins(1): "print -S Place the results in the history list instead of on the standard output. In this case only a single argument is allowed; it will be split into words as if it were a full shell command line. The effect is similar to reading the line from a history file with the HIST_LEX_WORDS option active."


A widgetification of @mpy's answer, add this to your .zshrc

to-history() { print -S $BUFFER ; BUFFER= }
zle -N to-history
bindkey 'œ' to-history

Note: œ is what I get on a Mac for alt/option-q, adjust for your terminal


If you're using vi mode, then press ESC to enter normal mode, and then Shift+3 (#). This will put the commented out command in history.