bash 未在 shell 脚本中的函数内设置全局变量值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26760317/
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
global variable value not set inside a function in shell script
提问by nantitv
I have two shell script like as follows:
我有两个 shell 脚本,如下所示:
a.sh
灰
tes=2
testfunction(){
tes=3
echo 5
}
testfunction
echo $tes
b.sh
b.sh
tes=2
testfunction(){
tes=3
echo 5
}
val=$(testfunction)
echo $tes
echo $val
In first script tes
value is '3' as expected but in second it's 2?
在第一个脚本中,tes
正如预期的那样,值是“3”,但在第二个脚本中,它是 2?
Why is it behaving like this?
为什么会这样?
Is $(funcall)
creating a new sub shell and executing the function? If yes, how can address this?
正在$(funcall)
创建一个新的子 shell 并执行该函数吗?如果是,如何解决这个问题?
回答by ISanych
$() and `` create new shell and return output as a result.
$() 和 `` 创建新的 shell 并作为结果返回输出。
Use 2 variables:
使用 2 个变量:
tes=2
testfunction(){
tes=3
tes_str="string result"
}
testfunction
echo $tes
echo $tes_str
output
输出
3
string result
回答by ISanych
Your current solution creates a subshell which will have its own variable that will be destroyed when it is terminated.
您当前的解决方案创建了一个子shell,它将拥有自己的变量,该变量将在终止时被销毁。
One way to counter this is to pass tes as a parameter, and then return* it using echo.
解决这个问题的一种方法是将 tes 作为参数传递,然后使用 echo 返回*它。
tes=2
testfunction(){
echo
}
val=$(testfunction $tes)
echo $tes
echo $val
You can also use the return
command although i would advise against this as it is supposed to be used to for return codes, and as such only ranges from 0-255.Anything outside of that range will become 0
您也可以使用该return
命令,尽管我建议不要这样做,因为它应该用于返回代码,因此范围只有 0-255。该范围之外的任何内容都将变为 0
To return a string do the same thing
返回一个字符串做同样的事情
tes="i am a string"
testfunction(){
echo " from in the function"
}
val=$(testfunction "$tes")
echo $tes
echo $val
Output
输出
i am a string
i am a string from in the function
*Doesnt really return it, it just sends it to STDOUT in the subshell which is then assigned to val
*并没有真正返回它,它只是将它发送到子shell中的STDOUT,然后分配给val