0

I'm a PHP programmer doing some BASH scripting and I'm not sure how global variables are working.

I want to increment the 3 variables for each line in a supplied file. However, when I get to the bottom, the variables are still set at 0. How do I access the variables that are incremented within the WHILE DO loop? I just want to echo them out at the end..

From what I understand we're in kornshell

#!/bin/bash

typeset -i i=0
typeset -i t1=0
typeset -i t2=0


sed 1d $1 |  \

while read word1 word2 word3 word4 word5 
do
        i=i+1
        t1=t1+$word4
        t2=t2+$word5
done

echo $i
echo $t1
echo $t2


exit 0

1 Answer 1

2

BASH FAQ entry #24: "I set variables in a loop. Why do they suddenly disappear after the loop terminates? Or, why can't I pipe data to read?"

Sign up to request clarification or add additional context in comments.

2 Comments

grouping them in a subshell worked great. Would like to hear from others if this is a best practice.
@Wes: There is no "best practice". Use whatever is appropriate for the situation. Each of the techniques shown at the link has an appropriate application. The simple script in your question will work with any of them. The problem with grouping everything in a subshell comes when your script gets complicated and you keep having to move the closing brace to encompass more, more, more. In Bash, I would use the process substitution technique more often. Sometimes though, you want to see the input side at the top and you don't need to use the variables later or you can put the loop in a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.