Bash Script - Variable Scope in Do-While loop

纵饮孤独 提交于 2019-12-02 08:52:19

问题


I have a do while loop where I am adding a variable to itself

while read line 
do
      let variable=$variable+$someOtherVariable
done
    return $variable

When I echo the value of $variable I get no output ...

Is this the correct way to add some value back to the variable itself (i.e. i = i+j) Also, in the context of bash scripting what is the scope in this case..


回答1:


The problem is that the variable is not visible outside of the scope (the assignment is not propagated outside the loop).

The first way that comes to mind is to run the command in a subshell and forcing the loop to emit the variable:

variable=$(variable=0; while read line; do variable=$((variable+someOtherVariable)); done; echo $variable)



回答2:


return returns an "exit" code, a number, not what you are looking for. You should do an echo.



来源:https://stackoverflow.com/questions/7719548/bash-script-variable-scope-in-do-while-loop

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