全局变量的值在 BASH 中不会改变

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1205605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:06:08  来源:igfitidea点击:

Value of global variable doesn't change in BASH

linuxbashscripting

提问by Viky

I am working on a BASH script which has a global variable. The value of the variable changes in a function/subroutine. But the value doesnt change when I try to print that variable outside the function. The Sample code is as follows:

我正在处理一个具有全局变量的 BASH 脚本。变量的值在函数/子程序中发生变化。但是当我尝试在函数外部打印该变量时,该值不会改变。示例代码如下:

#!/bin/bash

count=

linux_f()
    {
        let count=100
    }

linux_f

echo $count

The echo statement prints blank and not 100 Why the value of the global variable doesn't traverse in the function and out.

echo 语句打印空白而不是 100 为什么全局变量的值没有在函数中遍历和遍历。

回答by

Your code works for me, printing 100. This is the code I used:

你的代码对我有用,打印 100。这是我使用的代码:

count=

linux_f()
    {
        let count=100
    }

linux_f

echo $count

Edit:I have tried this with version 2 of bash on MSYS and version 3 on Fedora Linux and it works on both. Are you really sure you are executing that script? Try putting an echo "this is it" in there just to make sure that something gets displayed. Other than that, I'm at a loss.

编辑:我已经在 MSYS 上的 bash 版本 2 和 Fedora Linux 上的 bash 版本 3 上尝试过这个,它适用于两者。你真的确定你正在执行那个脚本吗?尝试在那里放一个回声“就是这样”,以确保显示某些内容。除此之外,我一无所获。

回答by innaM

Perhaps because you are assigning to countland not to count?

也许是因为您正在分配给countl而不是给count

回答by dsm

There is a spelling mistake in that variable assignment (inside the function). Once fixed it will work:

变量赋值中有拼写错误(在函数内部)。一旦修复,它将起作用:

[dsm@localhost:~]$ var=3
[dsm@localhost:~]$ echo $var
3
[dsm@localhost:~]$ function xxx(){ let var=4 ; }
[dsm@localhost:~]$ xxx
[dsm@localhost:~]$ echo $var
4
[dsm@localhost:~]$ 

And run as a script:

并作为脚本运行:

[dsm@localhost:~]$ cat test.sh 
#!/bin/bash

var=
echo "var is '$var'"
function xxx(){ let var=4 ; }
xxx
echo "var is now '$var'"
[dsm@localhost:~]$ ./test.sh #/ <-- #this is to stop the highlighter thinking we have a regexp
var is ''
var is now '4'
[dsm@localhost:~]$