watch 命令不适用于特殊字符和引号

watch command not working with special characters and quotes

watch -n 1 "paste <(ssh ai02 'nvidia-smi pmon -s um -c 1') <(ssh ai03 'nvidia-smi pmon -s um -c 1' )"

上述命令用于将两个服务器 GPU 统计信息水平堆叠在一起。它在没有 watch 命令的情况下工作,但出现以下错误

sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `paste <(ssh ai02 'nvidia-smi pmon -s um -c 1') <(ssh ai03 'nvidia-smi pmon -s um -c 1' )'

您没有提供可重现的示例,但我想我设法制作了一个用于测试:

watch -n1 "paste <(seq -w 1000 | shuf -n '10' ) <(seq -w 1000 | shuf -n '10')"

输出类似的错误:

sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `paste <(seq -w 1000 | shuf -n '10' ) <(seq -w 1000 | shuf -n '1
0')'

为了更简单的解决这个问题,我们可以把sh -c改成bash -c:

watch -n1 -x bash -c 'paste <(seq -w 1000 | shuf -n "10" ) <(seq -w 1000 | shuf -n "10")'

来自 watch 手册:

-x, --exec
     Pass command  to exec(2) instead of  sh -c which reduces  the need to
     use extra quoting to get the desired effect.

如果您需要保留原始命令行中的撇号,您也可以转义:

watch -e -n1 -x bash -c 'paste <(seq -w 1000 | shuf -n '\''10'\'' ) <(seq -w 1000 | shuf -n '\''10'\'')'