Changing variables in a BASH while loop April 2, 2009

Posted by idimmu in linux.
There is an error that I often run in to when working with files and while loops in BASH. Often I have scripts similar to the following, where I cat a file and read it in using a while loop to process variables in the file:


#!/bin/bash

count=0;

cat testfile | while read line
do
count=$(($count+1));
echo $count;
done

echo "Total $count";


and using the following test data in testfile as:


cake
pie
thongs


I would expect an output like:


1
2
3
Total 3


But instead I get:


idimmu@boosh:~$ ./t.sh
1
2
3
Total 0


What is happening is due to the | (pipe) bash is forking and creating a new process so any variables we are altering and changing ($count) are being manipulated in the child process, and then lost when the subprocess finishes!

A lot of people I've spoken to who have seen this either completely change their code structure to accommodate, or worse, change shell completely to something like KSH!

If we tweak our script ever so slightly, and read the file in at the end of the BASH while loop...


#!/bin/bash

count=0;

while read line
do
count=$(($count+1));
echo $count;
done < testfile

echo "Total $count";


everything changes :)


idimmu@boosh:~$ ./t.sh
1
2
3
Total 3


and we get the output we expect! An excellent book on how to actually use BASH can be found here: Learning the bash Shell: Unix Shell Programming (In a Nutshell (O'Reilly))!

Tags

Friends

twitter

  • @jooli2 I just wanted to see what @dpashley looked like after a pint of the black stuff, turns out he looks ugly!
  • looking forwards to performing at Burning The Clocks next Wednesday :o Come all and come watch!
  • @journoannie are they giant sad puppy eyes, as that could be kind of cute? Although the whole self pity thing is a bit of a turn off!
  • Elgg 1.8 Tidypics Group Fix http://t.co/C2D56UsH
  • BackupPC ping too slow http://t.co/9Na2PxKs

lastfm

  • Bogart Shwadchuck – Bitch Go Buy Me A Hot Dog (I'll Be Waiting Here, Doing The Robot)
  • Ill Nillas – What Up Bitches
  • M9 – Mental Prison (Feat. Phoenix Da Icefire) (Produced By Chemo)
  • Therapy? – A Moment Of Clarity
  • Therapy? – Unbeliever
  • Therapy? – Die Laughing
  • Finger Eleven – Swallowtail
  • Equilibrium – Mana
  • Equilibrium – Dämmerung
  • Equilibrium – Ruf In Den Wind

IdleRPG Stats

  • 1 webvictim 57
  • 2 HRH_H_Crab 57