在处理一个与此无关的(Python)脚本时,我遇到了一种非常奇怪的行为,涉及watch
和ps aux
,当后者通过管道传输到其他东西时。
我已设法将问题简化为一行。运行时
watch "ps aux | grep 'ps aux'"
在终端中,您通常会得到几行输出,正如预期的那样。
请注意,顶部三行被截断,刚好适合ps aux
末尾。当您将终端尺寸缩小到不再适合时,它将被完全从结果中删除。
这意味着 grep 只接收截断的输出。我发现最令人困惑的是这种情况发生的范围极其有限。以下两种情况都不会发生
ps aux | grep "ps aux"
watch "ps u -C ps"
watch "ssh localhost 'ps aux | grep \"ps aux\"'"
在所有这些情况下,列表都会按预期循环。
在 Ubuntu 15.04 上,bash 和 sh 似乎都是这种情况。
虽然我设法在脚本中解决了这个问题,但有人可以解释这种行为吗?
答案1
鼻恶魔。1
man ps
说(重点是我的):
comm COMMAND command name (only the executable name).
Modifications to the command name will not be
shown. A process marked is partly
dead, waiting to be fully destroyed by its
parent. The output in this column may contain
spaces. (alias ucmd, ucomm). See also the args
format keyword, the -f option, and the c option.
When specified last, this column will extend to
the edge of the display. If ps can not determine
display width, as when output is redirected
(piped) into a file or another command, the
output width is undefined (it may be 80,
unlimited, determined by the TERM variable, and
so on). The COLUMNS environment variable or
--cols option may be used to exactly determine
the width in this case. The w or -w option may
be also be used to adjust width.
事实上,COLUMNS
手动设置变量有帮助:
watch "ps aux | grep 'ps aux'"
COLUMNS=2000 watch "ps aux | grep 'ps aux'"
1即使我们没有谈论 C 编译器……