Scripting‎ > ‎Linux shell‎ > ‎

Shell: variable lost after loop

Thank you for visiting this page, this page has been update in another link Shell variable lost after loop
Shell scripting is easy, but variable lost issue pops up 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.

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, redirect before the loop

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

cat ./datafile
1
2
3
4
5



Comments