You are not logged in.

#1 2009-08-22 08:44:36

bharani
Member
From: Karaikudi, India
Registered: 2009-07-12
Posts: 202

[Solved]Using global variables

I am writing a simple bash script to read a file line by line and add all the last words in the file.

tt=0
pline(){  
    shift $(($# - 1)) 
    tt=$(($tt+$1))    
        }
cat cc.list | while read line; do
pline $line
done 
echo $tt

The cc.list file is

pen 10
pencil 50
rubber 5

I want the echo to print 65 as the result. But it is always printing 0.
Please help me.

Last edited by bharani (2009-08-22 10:09:35)


Tamil is my mother tongue.

Offline

#2 2009-08-22 09:05:59

majiq
Member
Registered: 2009-03-06
Posts: 259

Re: [Solved]Using global variables

I was beating myself over the head trying to figure this out...

http://tldp.org/LDP/abs/html/subshells.html#SUBSHELL
http://www.nucleardonkey.net/blog/2007/ … _bash.html

tl;dr: You're doing it fine, but the pipe makes a subshell in which the tt that is used is destroyed by the time the loop is finished.

Edit:

I should've thought to suggest ways around this. Try

#!/bin/bash
tt=0
pline(){
    shift $(( $# - 1 )) 
    tt=$(($tt+$1))
        }
while read line; do
pline $line
done < cc.list
echo $tt

Last edited by majiq (2009-08-22 09:13:44)

Offline

#3 2009-08-22 10:09:07

bharani
Member
From: Karaikudi, India
Registered: 2009-07-12
Posts: 202

Re: [Solved]Using global variables

Thank you.
I used this script after reading your post( before you edited it)

tt=0
pline(){  
    shift $(($# - 1)) 
    tt=$(($tt+$1))    
        }
 exec<$1
while read line
do
pline $line
done 
echo "Total is " $tt

Last edited by bharani (2009-08-22 10:10:34)


Tamil is my mother tongue.

Offline

Board footer

Powered by FluxBB