Shell: variable lost after loop

Shell scripting is easy, but variable lost issue pops up quite often when you do a bit complicated things.
For example, you want to do  a file scan for some particular thing

you do
cat /tmp/aaa | while read line;
do
<your process code here>
done

Then you will realize that all result will be gone after loop is done.

This is because '|' created a subshell, which cause two processes do not share the same set of variable.

IO Redirection

Use '< <( cmd )' to feed the file to the loop.

Here is an example that it checks an/several application status(multiple lines output) 

#!/bin/bash
  $debug=1
  while read line ; do
     i=0
     for var in $line
       do
          col[i]=$var
          i=$((i+1))
     done
     if [ ${col[1]} != "STATUS" ]; then
       if [ ${col[1]} == "running" ] ; then
          if [ $debug -eq 1 ] ; then
              echo -e "\e[0;32m Succeed \e[0m ${col[0]} ${col[1]}"
          fi
       else
          echo -e "\e[0;31m Error! \e[0m ${col[0]} ${col[1]}"
          ret=1
       fi
     fi
  done< <($status status)

Similarily, you can do io redirect before the loop

#!/bin/bash
exec < ./datafile
i=0
while read line;do
  i=`expr $i + $line`
done
echo $i

More IO redirection, see io redirection

 

Comments powered by CComment