9

Is there a way to modify the command that is about to execute? I would like to redirect the output to a file, as well as print it on the terminal. I found that ls > file.txt | cat does the job, so I would like to add that > file.txt | cat to any command that is about to execute.
Is there a better way to redirect to file and print to terminal? I am trying to make a logger.

4

2 回答 2

9

您可以更改执行行时执行的操作以更改将要执行的命令。这可以通过定义一个函数来完成,然后将其绑定到回车键。

让我们首先定义一个可以添加 '> file.txt | 的函数。cat' 以任何命令结尾:

function log_and_accept {
    BUFFER="$BUFFER > file.txt | cat"
    zle accept-line
}

下一部分是用您的新功能实际替换默认的输入键行为。我们要替换的默认行为是accept-line 函数,如果我们查看zle 文档,您会看到accept-line 绑定到^J 和^M。

要将此函数绑定到这些字母,您首先需要将其转换为小部件:

zle -N log_and_accept_widget log_and_accept

然后你可以绑定它,替换旧的行为:

bindkey '^J' log_and_accept_widget
bindkey '^M' log_and_accept_widget

现在,您将为您执行的每个命令扩展该命令。每个 cd、ls、vim 等。因此,我建议您定义更多函数来实际打开和关闭它:

function turn_on_logging {
    bindkey '^J' log_and_accept_widget
    bindkey '^M' log_and_accept_widget
}
function turn_off_logging {
    bindkey '^J' accept-line
    bindkey '^M' accept-line
}

zle -N turn_on_logging_widget turn_on_logging
zle -N turn_off_logging_widget turn_off_logging

bindkey '^P' turn_on_logging_widget
bindkey '^O' turn_off_logging_widget

我认为你应该小心这个。经过一番测试后,我很快就开始不喜欢它了。

于 2013-01-31T20:22:52.270 回答
1

有几种方法可以做到这一点,我最喜欢的 1 是我在这里找到的这个块http://git.grml.org/?p=grml-etc-core.git;a=blob_plain;f=etc/zsh /zshrc;hb=头

abk=(
  '...'  '../..'
  '....' '../../..'
  'BG'   '& exit'
  'C'    '| wc -l'
  'G'    '|& grep '${grep_options:+"${grep_options[*]}"}
  'H'    '| head'
  'Hl'   ' --help |& less -r'    #d (Display help in pager)
  'L'    '| less'
  'LL'   '|& less -r'
  'M'    '| most'
  'N'    '&>/dev/null'           #d (No Output)
  'R'    '| tr A-z N-za-m'       #d (ROT13)
  'SL'   '| sort | less'
  'S'    '| sort -u'
  'T'    '| tail'
  'V'    '|& vim -'
  'co'   './configure && make && sudo make install'
  'fc'   '> file.txt | cat'
)

zleiab() {
  emulate -L zsh
  setopt extendedglob
  local MATCH

  if (( NOABBREVIATION > 0 )) ; then
      LBUFFER="${LBUFFER},."
      return 0
  fi

  matched_chars='[.-|_a-zA-Z0-9]#'
  LBUFFER=${LBUFFER%%(#m)[.-|_a-zA-Z0-9]#}
  LBUFFER+=${abk[$MATCH]:-$MATCH}
}

zle -N zleiab && bindkey ",." zleiab

另请注意,我已添加'fc' '> file.txt | cat'到列表中abk

这样做的原因是您fc在命令后键入,然后,.快速连续点击(逗号和句点),zsh 将替换fc> file.txt | cat

于 2013-01-16T02:59:10.117 回答