简体   繁体   中英

Checking output of multiple variables in bash

Right now I have multiple commands defined as variables in my bash script like so:

LSIBATTSTATE=`/var/lib/einarc/tools/lsi_megacli/cli -AdpBbuCmd -GetBbuStatus -aALL | grep 'Operational'`
LSIBATT=`/var/lib/einarc/tools/lsi_megacli/cli -AdpBbuCmd -GetBbuStatus -aALL | grep 'isSOHGood: Yes'`
LSIWB=`/var/lib/einarc/tools/lsi_megacli/cli -LDinfo -Lall -Aall | grep 'WriteBack'`
ADAPZMM=`einarc ad info | grep 'ZMM Optimal'`

This is 4 of them, but there is the potential for there to be more. (This is for a RAID controller).

What I want to do is figure out how I can check the output of all of these variables for return results. Basically, something sort of like this without having to do an if/then statement for each:

ps cax | grep httpd > /dev/null
  if [ $? -eq 0 ]; then
  <do some stuff>
fi

If the desired output is found, then the script just moves on and ignores it. However, if the desired output isn't found (ie the return result is empty) then I want it to perform an action. I'm thinking that the only way to really do this in bash is with a for loop, but I'm not certain if that's the best or most efficient way. Also, would an array be of any use in this scenario? It doesn't seem like it to me, but there's still a lot of things I'm not as great at as I'd like to be in bash.

Any help would be appreciated.

This puts all the results in an array, and then iterates over it looking for any empty results.

results=("`/var/lib/einarc/tools/lsi_megacli/cli -AdpBbuCmd -GetBbuStatus -aALL | grep 'Operational'`" 
         "`/var/lib/einarc/tools/lsi_megacli/cli -AdpBbuCmd -GetBbuStatus -aALL | grep 'isSOHGood: Yes'`" 
         "`/var/lib/einarc/tools/lsi_megacli/cli -LDinfo -Lall -Aall | grep 'WriteBack'`
ADAPZMM=`einarc ad info | grep 'ZMM Optimal'`" )
all_succeeded=1
for result in "${results[@]}"; do
  if [ -z "$result" ]
  then echo Something failed.
       all_succeeded=0
       break
  fi
done

the test command allows compound statements. If you just want to check that each of the strings is non-empty:

if [ -z "$LSIBATTSTATE" -o -z "$LSIBATT" -o -z "$LSIWB" -o -z "$ADAPZMM" ]; then
  [error stuff]
fi

If you want something a little bit more extensible, you could run an array or sum of result codes:

Initialize

RESULTS=()
RESULTSUM=0

Update after each command

RESULT=$?
RESULTS[${#RESULTS[*]}]=$RESULT
RESULTSUM=$(($RESULTSUM + $RESULT))

Then after they are all done:

if [ $RESULTSUM -eq 0 ]; then
  [error stuff which can use $RESULTS array to know which command failed]
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM