2022-09-05更新:

2022-09-05更新:

私の関連記事何年も前に、私は、誤って実行しないように、bash 履歴に保存された「危険な」コマンドをコメントアウトする方法を見つけました。

同じことを実装するための最善の解決策は何でしょうかzsh?

zshこの目的に使用できる機能をいくつか提供していますか?zshより柔軟性が高いため、 ではこれが簡単になると思いますzsh

参考までに、私が使用しているのは次のものですbash(Stéphane Chazelas からの承認済み回答に基づく):

fixhist() {
   local cmd time histnum
   cmd=$(HISTTIMEFORMAT='<%s>' history 1)
   histnum=$((${cmd%%[<*]*}))
   time=${cmd%%>*}
   time=${time#*<}
   cmd=${cmd#*>}
   case $cmd in
     (cp\ *|mv\ *|rm\ *|cat\ *\>*|pv\ *|dd\ *)
       history -d "$histnum" # delete
       history -a
       [ -f "$HISTFILE" ] && printf '#%s\n' "$time" " $cmd" >> "$HISTFILE";;
     (*)
       history -a
   esac
   history -c
   history -r
}

2022-09-05更新:

受け入れられた解決策は機能しますが、意図しない副作用があります。insert-last-wordキーバインディングが台無しになります。以下に簡単な説明を示します。

私は「危険な」コマンドの 1 つを使用します。

rm zz

コメント付きで履歴に追加されました (希望どおり):

history
...
# rm zz

履歴に別のコマンドを追加してみましょう

echo foo

Altそして、 +を使って履歴を循環させたい場合.、次の結果が得られます。

echo <Alt> + .

foo
history
# rm zz

提供される代わりにzz、コメントされたコマンド全体が提供されます# rm zz

これをどうすれば修正できますか?

答え1

はい、zshaddhistoryフック関数を使用して、通常の履歴処理を無効にします。

function zshaddhistory() {
  # defang naughty commands; the entire history entry is in $1
  if [[ $1 =~ "cp\ *|mv\ *|rm\ *|cat\ *\>|pv\ *|dd\ *" ]]; then
    1="# $1"
  fi
  # write to usual history location
  print -sr -- ${1%%$'\n'}
  # do not save the history line. if you have a chain of zshaddhistory
  # hook functions, this may be more complicated to manage, depending
  # on what those other hooks do (man zshall | less -p zshaddhistory)
  return 1
}

zsh 5.0.8でテスト済み

% exec zsh
% echo good
good
% echo bad; rm /etc 
bad
rm: /etc: Operation not permitted
% history | tail -4
  299  exec zsh
  300  echo good
  301  # echo bad; rm /etc
  302  history | tail -4
%   

extendedhistoryこれはオプション セットでも機能するようです。

答え2

次の関数は thrig の関数に基づいており、次の点を修正しますhistignorespace

function zshaddhistory() {
  if [[ $1 =~ "^ " ]]; then
    return 0
  elif [[ $1 =~ "cp\ *|mv\ *|rm\ *|cat\ *\>|pv\ *|dd\ *" ]]; then
    1="# $1"
  fi
  # write to usual history location
  print -sr -- ${1%%$'\n'}
  # do not save the history line. if you have a chain of zshaddhistory
  # hook functions, this may be more complicated to manage, depending
  # on what those other hooks do (man zshall | less -p zshaddhistory)
  return 1
}

関連情報