SUMMARY: Shell script problem
2007-12-25 0:43:00
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 at percipia.com>
To: <codeprof at codeprof.com>
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
> _______________________________________________
> codeprof mailing list
> codeprof at codeprof.com
> http://www.codeprof.com/execute/ask/?codeinfoid=20970
Comments
Got something to say?
You must be logged in to post a comment.

