ZSH:进入时的行为

Aug*_*ger 5 unix linux shell zsh

我意识到,当我在我的终端中时,我希望在我使用 git 存储库时按Enter空输入来制作 als或 a git status

我怎样才能做到这一点?我的意思是,Empty input -> Enter在 zsh 中有自定义行为吗?


编辑:感谢您的帮助。这是我的看法preexec...

precmd() {
  echo $0;
  if ["${0}" -eq ""]; then
    if [ -d .git ]; then
      git status
    else
      ls
    fi;
  else
    $1
  fi;
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*hon 7

Enter zsh上调用accept-line小部件,这会导致缓冲区作为命令执行。

您可以编写自己的小部件以实现您想要的行为并重新绑定Enter

my-accept-line () {
    # check if the buffer does not contain any words
    if [ ${#${(z)BUFFER}} -eq 0 ]; then
        # put newline so that the output does not start next
        # to the prompt
        echo
        # check if inside git repository
        if git rev-parse --git-dir > /dev/null 2>&1 ; then
            # if so, execute `git status'
            git status
        else
            # else run `ls'
            ls
        fi
    fi
    # in any case run the `accept-line' widget
    zle accept-line
}
# create a widget from `my-accept-line' with the same name
zle -N my-accept-line
# rebind Enter, usually this is `^M'
bindkey '^M' my-accept-line
Run Code Online (Sandbox Code Playgroud)

zle accept-line虽然仅在实际有命令的情况下运行就足够了,但 zsh不会在输出后添加新的提示符。虽然可以使用 重绘提示zle redisplay,但如果您使用多行提示,这可能会覆盖输出的最后一行。(当然也有解决方法,但没有什么比使用zle accept-line.

警告:这会重新定义 shell 的(最?)重要部分。my-accept-line虽然这本身没有任何问题(否则我不会将其发布在这里),但如果不能完美运行,它很有可能使您的 shell 无法使用。例如,如果zle accept-line缺少,则无法使用Enter确认任何命令(例如重新定义my-accept-line或启动编辑器)。因此,请在将其放入您的~/.zshrc.

另外,默认情况下也accept-line绑定到Ctrl+ 。J我建议保留这种方式,以便有一种简单的方法来运行默认的accept-line.