업데이트 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. 여기 간단한 설명이 있습니다:

나는 "위험한" 명령 중 하나를 사용합니다:

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
}

관련 정보