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

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

问题描述

我正在处理这个:

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"

哪个返回:

hello
4

但是如果我把函数的结果赋值给一个变量,全局变量e不会被修改:

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"

返回:

hello
2

我听说过在这种情况下使用 eval,所以我在 test1:

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

eval 'e=4'

但结果相同.

你能解释一下为什么没有修改吗?如何在 ret 中保存 test1 函数的回声并修改全局变量?

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?

推荐答案

当您使用命令替换(即 $(...) 构造)时,您正在创建一个子 shell.子shell 从它们的父shell 继承变量,但这只有一种方式:子shell 不能修改其父shell 的环境.

When you use a command substitution (i.e., 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.

您的变量 e 是在子 shell 中设置的,但不是在父 shell 中设置的.有两种方法可以将值从子 shell 传递到其父级.首先,您可以将某些内容输出到 stdout,然后使用命令替换来捕获它:

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"

以上输出:

Hello

对于 0 到 255 范围内的数值,您可以使用 return 将数字作为退出状态传递:

For a numerical value in the range of 0 through 255, you can use return to pass the number as the exit status:

mysecondfunc() {
    echo "Hello"
    return 4
}

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

echo "$var - num is $num_var"

输出:

Hello - num is 4

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

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