scope of variable in pipe

后端 未结 6 1481
余生分开走
余生分开走 2020-12-18 10:51

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

6条回答
  •  独厮守ぢ
    2020-12-18 11:20

    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.

    See: 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
    

提交回复
热议问题