TransWikia.com

Put a command in history without executing it

Super User Asked by Dan Hulme on March 3, 2021

In , 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 ? 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.

4 Answers

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

Correct answer by Dennis on March 3, 2021

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.

Answered by pjboro on March 3, 2021

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

Answered by Mike on March 3, 2021

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

Answered by mpy on March 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP