简体   繁体   English

eval“ $(cat config_file | ./print_to_env_variables.py)”在函数中不起作用

[英]eval “$(cat config_file | ./print_to_env_variables.py)” not working from within a function

I have a simple bash script that is using a config.ini file that looks like this: 我有一个使用如下config.ini文件的简单bash脚本:

[a]
b=1
c=2
...

In the bash script, I sometimes do eval "$(cat config_file | ./print_to_env_variables.py)" where the python script is this: 在bash脚本中,有时我会eval "$(cat config_file | ./print_to_env_variables.py)" ,其中python脚本是这样的:

config = ConfigParser()
config.readfp(sys.stdin)
for sction in config.sections():
    print('declare -A {}'.format(sction))
    for k, v in config.items(sction):
        print("{}[{}]={}'.format(sction, k ,v))

Now, what this script does, is to add all sections into env variables, allowing me to use them from bash like this: echo "${a[b]}" 现在,此脚本的作用是将所有部分添加到env变量中,使我可以像这样通过bash使用它们: echo "${a[b]}"

This only works if I do it like: 仅当我这样做时才有效:

  1. eval... 评估...
  2. check the variable 检查变量

but if I: 但是如果我:

  1. call a function that does the eval (less code dup) 调用执行eval的函数(减少代码重复)
  2. check... 校验...

The variable does not exist. 该变量不存在。

Why is that? 这是为什么?

declare in a shell function declares a local variable that doesn't exist outside the function. declare在一个shell函数声明不会在函数外存在一个局部变量。 To declare a global variable, you must add the -g switch. 要声明全局变量,必须添加-g开关。 See help declare or man bash . 请参阅help declareman bash

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM