2

People mentioned using preexec hook in zsh, but how exactly should I use it? I mean, okay I can check for every command whether or not it's the command I want to not show up in history, but what to do after that?

3

By default zsh always keeps the last command in session history, even when setting HISTSIZE=0. You could write your own widget to circumvent the history mechanism.

sneaky-run () {   
    echo
    eval $BUFFER
    BUFFER=''
    zle reset-prompt
}

zle -N sneaky-run
bindkey '^X^M' sneaky-run

This the widget sneaky-run will run the currently typed command, then empty the command buffer and reset the prompt. Commands that are run within a widget are not added to the history.

The echo at the beginning is needed so that the output starts in a new line. If you have a multi-line prompt you may need to add additional echos for each additional line just before zle reset-prompt, otherwise the prompt might overwrite a few lines of the command output.

For this example sneaky-run is bound to the key combination Ctrl+X, Enter.


If you do not want to use an extra key combination for that, you can also wrap the accept-line widget, which is usually bound to Enter

accept-line-with-sneaky () {   
    if [[ "$BUFFER" == "${BUFFER#" } ]] ; then
        zle accept-line
    else
        echo
        eval $BUFFER
        BUFFER=''
        zle reset-prompt
    fi
}

zle -N accept-line-with-sneaky
bindkey '^M' accept-line-with-sneaky

This mimics the behavior of setting HIST_IGNORE_SPACE: If a command starts with a space, it will not be added to the history. But other than with HIST_IGNORE_SPACE it will also not be available when pressiong Up.

Note: this will override one of the most fundamental key bindings of zsh. So please test thoroughly before putting this in your ~/.zshrc.

2

You should use the HIST_IGNORE_SPACE option.

setopt HIST_IGNORE_SPACE

or set it in your profile and then prefix the commands you don't want stored with a space.

4
  • @Dababi What should work setopt HIST_IGNORE_SPACE? Are you saying that you've started zsh with this option set, then entered some command prefixed with space, pressed enter and then pressed up key and your prompt isn't filled with the previous command? Jan 11 '17 at 21:41
  • yes it worked for me
    – Dababi
    Jan 11 '17 at 21:44
  • @user1685095 If you press Up immediately then the previous command is recalled, even if it began with a space. But if you enter another command then the command that began with a space is no longer accessible. Jan 11 '17 at 23:37
  • @Gilles I know. I want to enter only one command, that wouldn't be in history. Two isn't good enough. Jan 12 '17 at 5:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.