磁盘空间使用脚本错误 [英] Error on a disk space usage script
问题描述
我试图修改一些检查磁盘空间使用情况的脚本,但遇到以下错误:
I tried to modify a little script of checking disk space usage, and I faced the below error:
disk_space.sh: 32:[:使用:期望整数表达式
disk_space.sh: line 32: [: Use: integer expression expected
# Set alert limit, 90% we remove % for comparison
alert=90
# $1 is the partition name
# $5 is the used percentage
# Print the df -h, then loop and read the result
df -h | awk '{ print $1 " " $5 }' | while read output;
do
#echo $output
# Get partition name
partition=$(echo $output | awk '{ print $1 }')
#echo 'Partition: ' $partition
# Used space with percentage
useSpPer=$(echo $output | awk '{ print $2}')
#echo 'Used space %: ' $useSpPer
#used space (remove percentage)
useSp=$(echo -n $useSpPer | head -c -1)
#echo 'Used space digit: ' $useSp
# Recap
#echo $useSp ' has ' $partition
# -ge is greatter than or equal
if [ $useSp -ge $alert ]; then # THIS LINE 32
echo $partition 'is running out of space with '$useSpPer
#else
#echo 'Down'
fi
done
如果有人有想法,请先感谢并感谢
If anyone has an idea, appreciated it and thanks in advance
推荐答案
在脚本的顶部放置 set -x
,使其回显每一行在执行之前,这是调试Shell脚本的好方法-您几乎可以肯定会发现,这些变量之一(用于 [
命令中)未按预期设置
Putting set -x
at the top of your script so that it echoes each line before execution is a great way to debug shell scripts - you'll almost certainly find that one of those variables (used in the [
command) isn't being set as you expected.
这是一个很好的一般建议,但是,对于您已将问题定位到该问题的位置,将这一行放在行前可能已经足够好了(当然也不太冗长)。产生问题:
That's good general advice but, for this problem where you've localised the problem, it's probably good enough (and certainly less verbose) to place this line before the line generating the problem:
echo "DEBUG [$useSp]"
如果这样做,您会发现所检查的值根本不是数字值。这是因为 df -h
的输出看起来像这样:
If you do that, you'll find that the value you're checking is not a numeric value at all. That's because the output of df -h
looks something like this:
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 48G 4.9G 40G 11% /
/dev/sr0 71m 71M 0 100% /media/cdrom0
这意味着,对于第一行,您将把 Use
与您的限额和 [
不能很好地处理:
That means that, for the first line, you'll be comparing the word Use
against your limit and [
will not handle that well:
pax> if [ 20 -gt 10 ]; then echo yes; fi
yes
pax> if [ Use -gt 10 ]; then echo yes; fi
bash: [: Use: integer expression expected
修复非常简单。由于您不想对第一行进行任何操作,因此只需使用现有的 awk
即可将其过滤掉:
The fix is fairly simple. Since you don't want to do anything with the first line, you can just use your existing awk
to filter it out:
df -h | awk 'NR>1{print $1" "$5}' | while read output;
do
...
NR> 1
仅处理记录数字2,依此类推,跳过第一个。
The NR>1
only processes record numbers two and so on, skipping the first one.
这篇关于磁盘空间使用脚本错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!