shell – 管道中变量的范围

前端之家收集整理的这篇文章主要介绍了shell – 管道中变量的范围前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果使用率超过10%,以下shell脚本将检查磁盘空间并将变量diskfull更改为1
最后一个回显总是显示0
我在if子句中尝试了全局diskfull = 1但它没有用.
如果消耗的磁盘超过10%,如何将变量更改为1?
#!/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@H_404_5@
使用管道时,外壳接缝使用子外壳来完成工作.由于这些子shell不知道$diskfull,因此永远不会更改该值.

看到:
http://www.nucleardonkey.net/blog/2007/08/variable_scope_in_bash.html

修改了你的脚本如下.它适用于我,也应该适用于您的系统.

#!/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@H_404_5@
原文链接:https://www.f2er.com/bash/386965.html

猜你在找的Bash相关文章