以下 shell 脚本将检查磁盘空间并更改变量 diskfull
至 1
如果使用率超过 10%
最后一个回显总是显示 0
我试过 global diskfull=1
在 if 子句中,但它不起作用。
如何将变量更改为 1
如果消耗的磁盘超过 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
最佳答案
这是使用 while
的副作用在一个管道中。有两种解决方法:
1) 把 while
循环及其在单独作用域中使用的所有变量,如 levislevis86 所示
some | complicated | pipeline | {
while read line; do
foo=$( some calculation )
done
do_something_with $foo
}
# $foo not available here
2) 如果您的 shell 允许,请使用 进程替换您可以将管道的输出重定向到 while 循环的输入
while read line; do
foo=$( some calculation )}
done < <(some | complicated | pipeline)
do_something_with $foo
关于shell - 管道中变量的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1789750/