While loop to read values

Hi Everyone,

I am currently tasked with some reporting on various Unix based OSes. I have a script deployed that runs and grabs the information I am looking for, and has a bit of logic to output the desired result into a text file.

Example of my text file:

multiUsers=yes
availableDiskSpace=40
homeFolderSize=10G

So, the script that runs basically pulls info from a system, parses it to my desired output, then echoes it to a text file where I can later read it and report or take action on it. My idea was to use a while loop to read these values, then build in if then statements to do a task.

example script:

#!/bin/bash

# while loop example of reading a file

file=/var/reports.txt

cat ${file} | while read line ; do
    echo -e ${line};
      if [[ multiUsers == "yes" ]]
          then echo "has multiple human users"
      fi
      if [[ availableDiskSpace -lt 20 ]]
        then echo "the boot volume has less than 20% free space"
      fi
done

exit 0

I have tried numerous ways of doing this, and I honestly hardly ever use while loops so I know there are other ways to do this. Perhaps even better ways, but now that I cannot get it work I am pretty much forcing myself to learn why it is not working.

In my script I would take actions, but the echoes are there as place holders for other commands I may run, as I am in the testing phase.

Thanks,
ZB

In your loop you have a variable named line; you do not define the variables multiUsers and availableDiskSpace. So, your if statements will never match what you're looking for.

Try replacing:

cat ${file} | while read line ; do
    echo -e ${line};
      if [[ multiUsers == "yes" ]]
          then echo "has multiple human users"
      fi
      if [[ availableDiskSpace -lt 20 ]]
        then echo "the boot volume has less than 20% free space"
      fi
done

with something like:

while IFS='=' read var val
do      printf "%s=%s\n" "$var" "$val"
        if [ "$var" == "multiUsers" ] && [ "$val" == "yes" ]
        then    echo "has multiple human users"
        fi
        if [ "$var" == "availableDiskSpace" ] && [ "$val" -lt 20 ]
        then    echo "the boot volume has less than 20% free space"
        fi
done < "$file"