SUMMARY: Shell script problem

From: Sundaram Ramasamy <sun_at_percipia.com>
Date: Mon Mar 03 2003 - 10:17:16 EST
Thanks for every one who replied for this. While loop runs in the sub shell
there no way we can export the count value to parent shell.



Here is the few option use can use:



1.



http://www.faqs.org/faqs/unix-faq/faq/part3/section-8.html



2.

Warp while loop in a function



#!/bin/sh





count=0



myfunc() {

        while read oneLine ; do

            count=`expr ${count} + 1`

            echo "Line${count}: ${oneLine}"

            foo=$count

        done

}



myfunc < a.txt

echo "The total no. of lines in the file 'input.txt' is: ${count}"





3. Use ksh or bash shell



4. Write the while loop output into file and read it back.



count=0
while read oneLine
do
    count=`expr $count + 1`
    echo "Line${count}: ${oneLine}"
--> echo $count > /tmp/count
done < input.txt
--> count=`cat /tmp/count`
echo "The total no. of lines in the file 'input.txt' is: $count"





To check the creation of sub shell, we can use the following technique



#!/bin/sh
count=0
while read oneLine
do
    count=`expr $count + 1`
ps -f
    echo "Line${count}: ${oneLine}"
done < input.txt
echo "The total no. of lines in the file 'input.txt' is: $count"



Thanks

Sundaram



----- Original Message -----
From: "Sundaram Ramasamy" <sun@percipia.com>
To: <sunmanagers@sunmanagers.org>
Sent: Friday, February 28, 2003 9:21 AM
Subject: Shell script problem


> Hi All,
>
> The following Bourne shell program looses the value of variable $count
> outside the loop?  The program should have printed the right result "3"
but
> it did not.
> Do not suggest other ways of counting the lines in a file. That is not the
> issue. The issue is
> finding why a variable looses its value outside the loop.
>
> $ cat input.txt
> John Doe
> Carl Hooper
> Bertrand Russel
>
>
> $cat t.sh
> #! /bin/sh
>
> count=0
> while read oneLine
> do
>     count=`expr $count + 1`
>     echo "Line${count}: ${oneLine}"
> done < input.txt
> echo "The total no. of lines in the file 'input.txt' is: $count"
>
> $ t.sh
> Line1: John Doe
> Line2: Carl Hooper
> Line3: Bertrand Russel
> The total no. of lines in the file 'input.txt' is: 0
>
>
> Thanks
> SR
> _______________________________________________
> sunmanagers mailing list
> sunmanagers@sunmanagers.org
> http://www.sunmanagers.org/mailman/listinfo/sunmanagers
_______________________________________________
sunmanagers mailing list
sunmanagers@sunmanagers.org
http://www.sunmanagers.org/mailman/listinfo/sunmanagers
Received on Mon Mar 3 10:19:59 2003

This archive was generated by hypermail 2.1.8 : Thu Mar 03 2016 - 06:43:04 EST