bash 如何在bash中获取变量配置的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9553715/
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
how to get value of variable config in bash?
提问by Tomas Pruzina
I have a linux config file with with format like this:
我有一个 linux 配置文件,格式如下:
VARIABLE=5753
VARIABLE2=""
....
How would I get f.e. value of VARIABLE2 using standard linux tools or regular expressions? (I need to parse directory path from file). Thanks in advance.
如何使用标准 linux 工具或正则表达式获得 VARIABLE2 的 fe 值?(我需要从文件解析目录路径)。提前致谢。
回答by Jim Garrison
eval $(grep "^VARIABLE=" configfile)
will select the line and evaluate it in the current bash context, setting the variable value. After doing this, you will have a variable named VARIABLEwith value 5753. If no such line exists in the configfile, nothing happens.
将选择该行并在当前 bash 上下文中对其进行评估,设置变量值。执行此操作后,您将拥有一个以VARIABLEvalue命名的变量5753。如果配置文件中不存在这样的行,则不会发生任何事情。
回答by ДМИТРИЙ МАЛИКОВ
$> cat ./text
VARIABLE=5753
VARIABLE2=""
With perlregular expression grepcould match these value using lookbehindoperator.
随着perl正则表达式grep可以匹配使用这些值回顾后操作。
$> grep --only-matching --perl-regex "(?<=VARIABLE2\=).*" ./text
""
And for VARIABLE:
而对于VARIABLE:
$> grep --only-matching --perl-regex "(?<=VARIABLE\=).*" ./text
5753
回答by Dawngerpony
You could use the source(a.k.a. .) command to load all of the variables in the file into the current shell:
您可以使用source(aka .) 命令将文件中的所有变量加载到当前 shell 中:
$ source myfile.config
Now you have access to the values of the variables defined inside the file:
现在您可以访问文件中定义的变量的值:
$ echo $VARIABLE
5753

