Bash脚本 - Do-While循环中的变量作用域 [英] Bash Script - Variable Scope in Do-While loop

查看:592
本文介绍了Bash脚本 - Do-While循环中的变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

当我回显$变量的值时,我得不到输出......

这是将某个值添加回变量本身的正确方法(即i = i + j)
另外,在bash脚本的上下文中,这种情况下的作用域是什么..

解决方案

问题在于变量在作用域之外是不可见的(赋值不会传播到循环之外)。



首先想到的方法是运行命令在一个子shell中强制循环发出变量:

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


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..

解决方案

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)

这篇关于Bash脚本 - Do-While循环中的变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆