If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > Unix Shell Scripts > Variable scope and debugging

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 04-02-04, 09:59
rkrishnan73 rkrishnan73 is offline
Registered User
 
Join Date: Mar 2004
Posts: 10
Variable scope and debugging

Hi

How is a variable's scope handled in bash? Here's the code skeleton.

var=0
while read oneLine
do
# do some mathematics with $var
# and the value read from the file

echo $var # displays variable value correctly for each stage

done < $inputFile

echo "Loop done.. $var" # displays accumulated variable value as 0

When I write set -a var it works, but I'm unable to debug the script any more by specifying set -x. Can we not do both at the same time?

Thanks in advance.

- Ram.
Reply With Quote
  #2 (permalink)  
Old 04-02-04, 10:39
aigles aigles is offline
Registered User
 
Join Date: Jan 2004
Location: Bordeaux, France
Posts: 319
I am using cgywin bash and i don't have this problem :
Code:
Var=0
echo "Before loop Pid:$$ Var:$Var"
while read oneline
do
   ((Var += 1))
    echo "   Inside loop Pid:$$ Var:$Var"
done < a.a
echo "After loop Pid:$$ Var:$Var"
the result is :
Quote:
Before loop Pid:429381 Var:0
Inside loop Pid:429381 Var:1
Inside loop Pid:429381 Var:2
Inside loop Pid:429381 Var:3
Inside loop Pid:429381 Var:4
Inside loop Pid:429381 Var:5
Inside loop Pid:429381 Var:6
After loop Pid:429381 Var:6
Some version of shell creates a subprocess to execute the statements into the loop, in that case the modifications of the environment are lost when exiting the loop.
Try my script and verify that the Pid is the pid is the same outside and inside the loop.

You can also try to export your variable.
__________________
Jean-Pierre.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On