管道中的变量范围 [英] scope of variable in pipe
问题描述
以下外壳脚本将检查磁盘空间,如果使用率超过10%,则将变量diskfull
更改为1
最后的回声总是显示0
我在if子句中尝试了global diskfull=1
,但是它不起作用.
如果磁盘使用量超过10%,如何将变量更改为1
?
The following shell scrip will check the disk space and change the variable diskfull
to 1
if the usage is more than 10%
The last echo always shows 0
I tried the global diskfull=1
in the if clause but it did not work.
How do I change the variable to 1
if the disk consumed is more than 10%?
#!/bin/sh
diskfull=0
ALERT=10
df -HP | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
#echo $output
usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
partition=$(echo $output | awk '{ print $2 }' )
if [ $usep -ge $ALERT ]; then
diskfull=1
exit
fi
done
echo $diskfull
推荐答案
使用管道时,shell接缝将使用子shell进行工作.由于这些子外壳程序不知道$diskfull
,因此该值永远不会更改.
When using pipes the shell seams to use sub-shells to do the work. As $diskfull
is not known to these sub-shells the value is never changed.
请参阅: http://www.nucleardonkey.net/blog/2007/08/variable_scope_in_bash. html
我修改了您的脚本,如下所示.它对我有用,也应该在您的系统上工作.
I modified your script as follows. It works for me and should work on your system too.
#!/bin/sh
diskfull=0
ALERT=10
stats=`df -HP | grep -vE '^Filesystem|tmpfs|cdrom|none|udev' | awk '{ print $5 "_" $1 }'`
for output in $stats
do
usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
partition=$(echo $output | sed s/.*_// )
#echo $partition - $usep
if [ $usep -le $ALERT ]; then
diskfull=1
break
fi
done
echo $diskfull
这篇关于管道中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!