0

I am learning shell, I want to use shell script to check disk space and output value, but it doesn't work.

#!/bin/bash
result=""
ALERT=40

OUT_FLAG() {
        local check_value=$1
        local result_value=$2
        if [ ${check_value} -eq 0 ];then
             result="$result|${result_value}:0"
        else
             result="$result|${result_value}:1"
        fi
}
Check_disk() {
        local disk_result=0
        df -Pl | grep -vE "^Filesystem|tmpfs|cdrom" | awk '{print $5 " " $6}'|while read output;
        do
                usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1)
                if [ $usep -ge $ALERT ]; then
                disk_result=1
                fi
        done
        OUT_FLAG ${disk_result} "disk"

}
Check_disk
echo $result

I want it to output |disk:1 but it is |disk:0. Wanted to know if it's good practice to do that and what would be the best way to do that?

Echo_s
  • 11
  • 5

1 Answers1

0

The df -Pl | ... | while pipeline runs as a subshell, and disk_result is only being set in the subshell. After the done, disk_result retains the value it had outside the subshell. There are some shells in which this is not true, but it is the case in bash. The simplest solution is to expand the scope with something like:

    df -Pl | ... | { while read output;
    do ...; done; 
    OUT_FLAG "${disk_result}" disk; 
    }

By putting the call to OUT_FLAG (Note that OUT_FLAG is a terrible name for a function) inside the braces, it becomes part of the subshell, so disk_result is defined as you expect.

William Pursell
  • 204,365
  • 48
  • 270
  • 300