在 Bash 中的函数内部使用声明
我想使用函数更改全局变量(或至少附加到它)。
input="Hello"
example=input
func() {
declare -x $example="${input} World"
}
func
echo $input
其输出将是“Hello”的原始值。如果该函数能够更改原始值,我希望它。有没有其他方法可以完成此任务。请注意,我需要设置 example=input
然后对 example (变量)执行操作。
顺便说一句,如果我使用 eval
代替,该函数会抱怨 World 是一个函数或其他东西。
I am want to change a global variable (or at least append to it) using a function.
input="Hello"
example=input
func() {
declare -x $example="${input} World"
}
func
echo $input
The output of this would be "Hello" The original value. I would like it if the function were to able to change the original value. Is there alternative to accomplishing this. Please note I need to set example=input
and then perform on the operation on example (the variable).
BTW, if I used eval
instead the function will complain about World being a function or something.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您尝试过使用导出吗?
Did you try using export?
使用
你应该在你的
func
中请参阅
http://www.gnu.org/software/bash/manual/bashref。 html
另请注意,在 MinGW 中,似乎
declare
不支持-g
选项。you should use
in your
func
see
http://www.gnu.org/software/bash/manual/bashref.html
Also note in MinGW, it seems that
declare
does not support the-g
option.您可以通过重新定义 func() 来使用 eval,如下所示:
这允许双引号在第一次解析中“存活”(根据需要将变量扩展为其值),以便eval 再次开始解析字符串 'input="Hello World"。
至于使用
export
来完成这项工作,如果变量输入实际上不需要导出,则包含其 '-n' 选项:,并且该变量仍然是 shell 变量并且不会得到导出为环境变量。
You could use
eval
by redefining func() as the following:This allows the double-quotes to "survive" the first parsing (which expands the variables into their values, as needs to be done) so that eval starts parsing again with the string 'input="Hello World".
As for the use of
export
to do the job, if the variable input does not actually need to be exported, include its '-n' option:, and the variable remains a shell variable and does not get exported as an environment variable.