如何使用管道在表达式上执行 watch 命令?

Abd*_*red 10 command-line pipe shell-script watch

我今天学到了很棒的 shuf 命令:

ls | shuf  
Run Code Online (Sandbox Code Playgroud)

向我展示了工作目录的列表,但感谢 shuf 每次我用另一个命令执行这个管道命令表达式时。

所以我想,为什么不每一秒都重复这个表达,所以我尝试

watch -n1 ls | shuf          (and got no output)
watch -n1 (ls | shuf)        (and got an error)
watch -n1 {ls | shuf}        (and got an error)
Run Code Online (Sandbox Code Playgroud)

然后我把 ls | shuf 到它自己的文件中,并从中制作了一个脚本 foo 。

watch -n1 ./foo               (this times it worked)
Run Code Online (Sandbox Code Playgroud)

是否可以将 watch 命令应用于管道命令表达式,而无需将表达式制作成脚本文件?

Sté*_*las 11

watch 命令存在多种变体,其中一些会产生一个 shell 来解释由传递给的参数串联而成的命令行watch(中间有空格字符)。在那些你可以做:

watch 'ls | shuf'
Run Code Online (Sandbox Code Playgroud)

与...一样:

watch ls '|' shuf
Run Code Online (Sandbox Code Playgroud)

(那些watch实际上运行:"/bin/sh", ["sh", "-c", "ls | shuf"]并且非常危险,因为第二级解释可以在未预料到的情况下打开错误和安全问题的大门,procps-ng 的 watch 可以通过-x选项避免这种行为)。

还有一些只执行名称在第一个参数中给出的命令,并将所有参数作为参数。在那些:

watch sh -c 'ls | shuf'
Run Code Online (Sandbox Code Playgroud)