For Loop in shellscript - Printing Output for every iteration

for VGLIST in `lsvg -o`
do 
CLOSED_OUT=`echo $VGLIST | lsvg -l $VGLIST | awk '{print $6 "  " $7}' | grep closed`
if [[ $? = 0 ]]; then
    echo "Filesystems $CLOSED_OUT in VG that are in Closed status"
else
    echo "\n Some message"
fi

Above Code is working fine, but

echo "Filesystems $CLOSED_OUT in VG that are in Closed status"

is being printed for every iteration. I just want to print one line output for each filesystem that is closed in a particular volume group.

I never used $? to test a grep in a `subshell`. Does it return the grep $? in both ksh and bash? I would test 'if [ "$CLOSED_OUT" != "" ]' and put $VGLIST in the message. VGLIST seems a strange name for a list item.

1 Like

does lsvg actually read from stdin? This code looks needlessly convoluted...

1 Like

When I tested command line , $? returned 1 for the grep output while finding the closed file systems.
My requirement for this script is to find closed/syncd filesystems as non root user in all the volume groups OS being AIX 6.1. Please share your ideas so that I can follow along. Thank you.

Well, $? has a short shelf life, as everything under the sun sets it, so what works on a command line does not work on slightly more complex command line. It is commonly used something like:

some_command with_args_and_redirect
ret=$?
if [ $ret = 0 ]
then
 some action
fi

I like the pipes and all shell:

lsvg -o | while read VG
do
 lsvg -l $VG | while read x1 x2 x3 x4 x5 x6 x7 x8
 do
  case "$x7" in
  (closed)
     echo $VG $x6 Closed
    ;;
  (*)
     echo $VG $x6 OK
    ;;
  esac
 done
done
1 Like

Thank you DGPickett. This post is really helpful. I will have my code embedded to the example. This thread can now be closed.

Only because I can't sleep...

lsvg -o | while read VG
do
 lsvg -l $VG | while read -a x  
 do
  case "${x[6]}" in
  (closed)
     echo $VG ${x[5]} Closed
    ;;
  (*)
     echo $VG ${x[5]} OK
    ;;
  esac
 done
done
1 Like

Note: read -a is bash-only syntax

Plus, the form 'read x1 x2 xrest' allows you to capture the rest of the line intact without losing the nature of the white space or expending so many resources. But that is a very nice bash-ism!