如果引用的命令是准确的:
watch -n 0.2 'ps -p $(pgrep -d',' -x snmpd) -o rss= | awk '{ i += $1 } END { print i }''
^ ^ ^ ^ ^^
1 0 1 0 10
你的单引号有问题。1 表示“引用开始”,0 表示引用结束。以下命令行应该适合您:
watch -n 0.2 'ps -p $(pgrep -d"," -x snmpd) -o rss= | awk "{ i += $1 } END { print i }"'
^ ^
1 0
双引号$(...)
也可以正常工作。单引号字符串watch
作为一个整体发送。以前,您有多个参数。
请注意,在您的工作命令中,您有:
watch -n 0.2 'ps -p $(pgrep -d',' -x snmpd) -o rss'
^ ^ ^ ^
1 0 1 0
现在,因为中间 '01' 之间的字符是逗号,而不是空格,shell 继续给出watch
一个参数,但它不包含引号。watch
它的第三个论点是:
ps -p $(pgrep -d, -xsnmpd) -o rss
使用您的awk
-line, 1watch` 获得多个参数:
ps -p $(pgrep -d, -x snmpd) -o rss= | awk {
i
+=
$1
}
END
{
print
i
}
它不知道如何处理多余的东西。(注意: 的值$1
将是 shell 的当前值$1
(可能是一个空字符串,在这种情况下,对应的参数$1
将被省略。)
这个变体,$1
在awk
脚本中的之前有一个反斜杠,似乎对我有用(当我寻找一个实际正在运行的程序时——snmpd
它没有在我测试的机器上运行,因此事情崩溃了):
sh -c 'ps -p $(pgrep -d"," -x snmpd) -o rss= | awk "{ i += \$1 } END { print i }"'
If you think there's any danger that there is no snmpd
process, then you need to do things a little less compactly. That's the command I tested; you can put the watch -n 0.2
in place of the sh -c
. But note that the man page for watch
does explicitly say:
Note that command
is given to "sh -c
" which means that you may need to use extra quoting to get the desired effect.
That was very accurate!
If you prefer to stick with single quotes, you could try:
watch -n 0.2 'ps -p $(pgrep -d"," -x snmpd) -o rss= | awk '\''{ i += $1 } END { print i }'\'
The idea behind the '\''
motif is that the first single quote terminates the current single-quoted string; the backslash single quote adds an actual single quote, and the last single quote starts a new single-quoted string. The '\'
at the end could also be written '\'''
, but the last two single quotes are redundant, so I left them out.