The Computer Oracle

How to prevent a command in the zshell from being saved into history?

--------------------------------------------------
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: Switch On Looping

--

Chapters
00:00 How To Prevent A Command In The Zshell From Being Saved Into History?
00:16 Accepted Answer Score 121
00:50 Answer 2 Score 16
01:38 Thank you

--

Full question
https://superuser.com/questions/352788/h...

--

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

--

Tags
#commandline #zsh #linuxterminal

#avk47



ACCEPTED ANSWER

Score 121


Use the HIST_IGNORE_SPACE option.

setopt HIST_IGNORE_SPACE

man zshoptions

HIST_IGNORE_SPACE

Remove command lines from the history list when the first character on the line is a space, or when one of the expanded aliases contains a leading space. Note that the command lingers in the internal history until the next command is entered before it vanishes, allowing you to briefly reuse or edit the line. If you want to make it vanish right away without entering another command, type a space and press return.




ANSWER 2

Score 16


If you desire more granular control over what's added to ZSH history, you can define the zshaddhistory function in .zshrc. The following definition uses a regex to define a pattern to ignore:

function zshaddhistory() {
  emulate -L zsh
  if ! [[ "$1" =~ "(^ |^ykchalresp|--password)" ]] ; then
      print -sr -- "${1%%$'\n'}"
      fc -p
  else
      return 1
  fi
}

Note that the behavior from man zshopts under HIST_IGNORE_SPACE is still present:

Note that the command lingers in the internal history until the next command is entered before it vanishes, allowing you to briefly reuse or edit the line.

So to test it, you would have to hit an extra [Enter]. This removes the command both from the output of history, and also the ↑ arrow history.

See this plugin for keeping log entries, but mask sensitive data based on a regex: https://github.com/jgogstad/passwordless-history