The Computer Oracle

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

Become or hire the top 3% of the developers on Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Question
00:22 Accepted answer (Score 101)
01:12 Answer 2 (Score 12)
02:14 Thank you

--

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

Answer 1 links:
https://github.com/jgogstad/passwordless...

--

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