dar*_*iah 7 bash scripts 14.04
#!/bin/bash
SUBJECT="WARNING CPU USAGE HIGH"
TO=gmail id
MESSAGE=/tmp/messages
echo "#######################" > $MESSAGE
echo "CPU statistics as follows.." >> $MESSAGE
mpstat >> $MESSAGE
echo "#######################" >> $MESSAGE
CPU_USAGE=$(top -b -n1 | awk '/^Cpu/ {print $2}' | cut -d. -f1)
[ $CPU_USAGE -gt 85 ] && mail -s "$SUBJECT" "$TO" < $MESSAGE`
Run Code Online (Sandbox Code Playgroud)
./cpu.sh: line 11: [: -gt: unary operator expected
可能是什么原因
问题是它CPU_USAGE最终是一个空字符串。这会导致这里出现问题:
[ $CPU_USAGE -gt 85 ]
Run Code Online (Sandbox Code Playgroud)
对 shell 变量求值后,上面变成:
[ -gt 85 ]
Run Code Online (Sandbox Code Playgroud)
这失败了,因为-gt现在缺少之前的参数。
要获得非空CPU_USAGE,我们需要替换:
CPU_USAGE=$(top -b -n1 | awk '/^Cpu/ {print $2}' | cut -d. -f1)
Run Code Online (Sandbox Code Playgroud)
和:
CPU_USAGE=$(top -b -n1 | awk '/^%Cpu/ {print $2}' | cut -d. -f1)
Run Code Online (Sandbox Code Playgroud)
%添加了 a 的地方。
如上所述,当CPU_USAGE为空且未加引号时,我们会收到“一元运算符”错误:
$ CPU_USAGE=""; [ $CPU_USAGE -gt 85 ] && echo yes
bash: [: -gt: unary operator expected
Run Code Online (Sandbox Code Playgroud)
在这种情况下引用 shell 变量是最佳做法。如果我们引用它,那么我们会收到不同的错误消息:
$ CPU_USAGE=""; [ "$CPU_USAGE" -gt 85 ] && echo yes
bash: [: : integer expression expected
Run Code Online (Sandbox Code Playgroud)
虽然我们仍然收到错误消息,但此错误消息至少提供了更多信息:它表示这$CPU_USAGE不是数字。
该cut过程是不需要的。我们可以替换:
CPU_USAGE=$(top -b -n1 | awk '/^%Cpu/ {print $2}' | cut -d. -f1)
Run Code Online (Sandbox Code Playgroud)
和:
CPU_USAGE=$(top -b -n1 | awk -F'[ .]+' '/^%Cpu/ {print $2}')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5652 次 |
| 最近记录: |