为什么下面的方法不起作用?:while true; 做“$my_command”;睡眠 1; 完毕

Ame*_*ina 2 zsh shell-script

跟进这个问题的最佳答案,我想我可以:

1) 定义命令:

cmd='for x in $(my_command | grep keyword | cut -d" " -f1); do command2 "arguments" $x; done'
Run Code Online (Sandbox Code Playgroud)

2)如下循环运行

while true; do "$cmd"; sleep 1; done
Run Code Online (Sandbox Code Playgroud)

但是,以上不起作用,我得到以下信息

zsh: command not found for x in $(......
zsh: command not found for x in $(......
zsh: command not found for x in $(......
...
Run Code Online (Sandbox Code Playgroud)

任何想法为什么?

澄清:

如果我运行for x in $(my_command | grep keyword | cut -d" " -f1); do command2 "arguments" $x; done'它完美无缺。

附录:

我注意到,如果我使用eval,它会起作用,即:

while true; do eval "$cmd"; sleep 1; done
Run Code Online (Sandbox Code Playgroud)

cmd每秒运行一次命令

Gil*_*il' 7

如果要准备在同一个 shell 中运行的命令,请使用函数。

cmd () {
  for x in $(my_command | grep keyword | cut -d" " -f1); do
    command2 "arguments" $x
  done
}
while true; do cmd; sleep 1; done
Run Code Online (Sandbox Code Playgroud)