The Computer Oracle

Put a command in history without executing it

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping

--

Chapters
00:00 Put A Command In History Without Executing It
00:35 Accepted Answer Score 8
01:57 Answer 2 Score 10
02:32 Answer 3 Score 5
02:49 Answer 4 Score 1
03:02 Thank you

--

Full question
https://superuser.com/questions/561725/p...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#zsh

#avk47



ANSWER 1

Score 10


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."




ACCEPTED ANSWER

Score 8


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



ANSWER 3

Score 5


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




ANSWER 4

Score 1


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.