加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

shell – 管道中变量的范围

发布时间:2020-12-15 18:59:04 所属栏目:安全 来源:网络整理
导读:如果使用率超过10%,以下shell脚本将检查磁盘空间并将变量diskfull更改为1 最后一个回显总是显示0 我在if子句中尝试了全局diskfull = 1但它没有用. 如果消耗的磁盘超过10%,如何将变量更改为1? #!/bin/shdiskfull=0ALERT=10df -HP | grep -vE '^Filesystem|
如果使用率超过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
使用管道时,外壳接缝使用子外壳来完成工作.由于这些子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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读