如何在zsh中使用带有功能的手表?

nac*_*cab 2 zsh function watch

我想在watch调用中使用自定义函数。这是一个虚拟示例:

my_fun(){
    head -c2
}
echo hello | my_fun
# he
watch 'echo hello | my_fun'
# my_fun: command not found
Run Code Online (Sandbox Code Playgroud)

我怎么watch知道my_fun

vin*_*c17 6

watch实用程序使用sh -c. 所以,如果你想执行一个 zsh 函数,你需要显式地执行 zsh。例如,如果您的函数定义在/path/to/functions文件中,您可以执行以下操作:

watch 'echo hello | zsh -c "source /path/to/functions; my_fun"'
Run Code Online (Sandbox Code Playgroud)

或者

watch 'zsh -c "source /path/to/functions; echo hello | my_fun"'
Run Code Online (Sandbox Code Playgroud)

但是编写一个包含所有内容的脚本可能比 zsh 函数更好。