While Do loop and variables in a bash script?

ぐ巨炮叔叔 提交于 2019-12-23 06:00:10

问题


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:


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?"



来源:https://stackoverflow.com/questions/5176643/while-do-loop-and-variables-in-a-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!