LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   shell script returning counter value from a while loop - lost upon completion (https://www.linuxquestions.org/questions/programming-9/shell-script-returning-counter-value-from-a-while-loop-lost-upon-completion-770177/)

logan960 11-19-2009 05:29 AM

shell script returning counter value from a while loop - lost upon completion
 
Hi all

I need to know how to return a counter variable from a while loop.
Variable value is lost when exiting the while loop.

This is a stupid exacmple just to demonstrate the problem.

### ---------------------------- begin test.sh
typeset -x -i v=0

cat .bashrc | grep "^#alias" | while read line
do
v=`expr $v + 1`
echo "found $v $line"
done

echo "Total occurrences: $v"
### ---------------------------- end test.sh

When you run it, you'll get:

$ . test.sh
found 1 #alias ll='ls -l'
found 2 #alias la='ls -A'
found 3 #alias l='ls -CF'
Total occurrences: 0

Any help would be appreciated.

catkin 11-19-2009 05:41 AM

A classic bash "gotcha"!

When bash runs a pipeline it runs all but the first command in subshell(s) and any variables set in them are lost when the pipeline completes. Explained in more detail with workarounds here.

logan960 11-19-2009 06:30 AM

Thx catkin
 
This indeed does the trick.

# POSIX
linecnt=0
cat /etc/passwd |
{
while read -r line ; do
linecnt=$((linecnt+1))
done
echo "total number of lines: $linecnt"
}


All times are GMT -5. The time now is 12:59 AM.