如何修改bash中的函数内的全局变量? [英] How to modify a global variable within a function in bash?

查看:169
本文介绍了如何修改bash中的函数内的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  GNU bash,版本4.1.2(1) - 释放(x86_64-redhat -linux-gnu)

我有如下的脚本:

 #!/ bin / bash 

e = 2

function test1(){
e = 4
echohello
}

test1
echo$ e

返回:

  hello 
4

但是,如果我将函数的结果赋值给一个变量,那么全局变量 e 未修改:

 #!/ bin / bash 

e = 2

函数test1(){
e = 4
echohello
}

ret = $(test1)

echo$ ret
echo$ e

返回:

  hello 
2

在这种情况下,我听说使用eval ,所以我在 TEST1

  eval'e = 4'

但结果相同。



你能解释一下为什么它没有被修改吗?我怎样才能将 test1 函数的回声保存在 ret 中并修改全局变量?

$当您使用命令替换(即 $(...)构造)时, ,你正在创建一个子shell。子壳从其父壳中继承变量,但这只能用一种方式 - 子壳不能修改其父壳的环境。您的变量 e 设置在一个子shell中,但不是父shell。有两种方法可以将子外壳的值传递给父代。首先,你可以输出一些东西给stdout,然后用一个命令替换来捕获它:

  myfunc(){
echo 你好
}

var =$(myfunc)

echo$ var

授予:

 您好

对于0-255的数值,您可以使用 return 来传递数字作为退出状态:

  myotherfunc(){
echoHello
return 4
}

var =$(myotherfunc)
num_var = $?

echo$ var - num is $ num_var

授予:

  Hello  -  num是4 


I'm working with this:

GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

I have a script like below:

#!/bin/bash

e=2

function test1() {
  e=4
  echo "hello"
}

test1 
echo "$e"

Which returns:

hello
4

But if I assign the result of the function to a variable, the global variable e is not modified:

#!/bin/bash

e=2

function test1() {
  e=4
  echo "hello"
}

ret=$(test1)

echo "$ret"
echo "$e"

Returns:

hello
2

I've heard of the use of eval in this case, so I did this in test1:

eval 'e=4'

But the same result.

Could you explain me why it is not modified? How could I save the echo of the test1 function in ret and modify the global variable too?

解决方案

When you use a command substitution (ie the $(...) construct), you are creating a subshell. Subshells inherit variables from their parent shells, but this only works one way - a subshell cannot modify the environment of its parent shell. Your variable e is set within a subshell, but not the parent shell. There are two ways to pass values from a subshell to its parent. First, you can output something to stdout, then capture it with a command substitution:

myfunc() {
    echo "Hello"
}

var="$(myfunc)"

echo "$var"

Gives:

Hello

For a numerical value from 0-255, you can use return to pass the number as the exit status:

myotherfunc() {
    echo "Hello"
    return 4
}

var="$(myotherfunc)"
num_var=$?

echo "$var - num is $num_var"

Gives:

Hello - num is 4

这篇关于如何修改bash中的函数内的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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