如何在bash中获取变量配置的值? [重复]

时间:2022-07-20 23:39:59

This question already has an answer here:

这个问题在这里已有答案:

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.

我怎么会得到f.e.使用标准linux工具或正则表达式的VARIABLE2的值? (我需要解析文件中的目录路径)。提前致谢。

3 个解决方案

#1


4  

$> cat ./text 
VARIABLE=5753
VARIABLE2=""

With perl regular expression grep could match these value using lookbehind operator.

使用perl正则表达式,grep可以使用lookbehind运算符匹配这些值。

$> grep --only-matching --perl-regex "(?<=VARIABLE2\=).*" ./text
""

And for VARIABLE:

而对于VARIABLE:

$> grep --only-matching --perl-regex "(?<=VARIABLE\=).*" ./text
5753

#2


5  

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 VARIABLE with value 5753. If no such line exists in the configfile, nothing happens.

将选择该行并在当前bash上下文中对其进行评估,并设置变量值。执行此操作后,您将拥有一个名为VARIABLE的变量,其值为5753.如果配置文件中不存在此类行,则不会发生任何操作。

#3


4  

You could use the source (a.k.a. .) command to load all of the variables in the file into the current shell:

您可以使用source(a.k.a.)命令将文件中的所有变量加载到当前shell中:

$ source myfile.config

Now you have access to the values of the variables defined inside the file:

现在您可以访问文件中定义的变量的值:

$ echo $VARIABLE
5753

#1


4  

$> cat ./text 
VARIABLE=5753
VARIABLE2=""

With perl regular expression grep could match these value using lookbehind operator.

使用perl正则表达式,grep可以使用lookbehind运算符匹配这些值。

$> grep --only-matching --perl-regex "(?<=VARIABLE2\=).*" ./text
""

And for VARIABLE:

而对于VARIABLE:

$> grep --only-matching --perl-regex "(?<=VARIABLE\=).*" ./text
5753

#2


5  

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 VARIABLE with value 5753. If no such line exists in the configfile, nothing happens.

将选择该行并在当前bash上下文中对其进行评估,并设置变量值。执行此操作后,您将拥有一个名为VARIABLE的变量,其值为5753.如果配置文件中不存在此类行,则不会发生任何操作。

#3


4  

You could use the source (a.k.a. .) command to load all of the variables in the file into the current shell:

您可以使用source(a.k.a.)命令将文件中的所有变量加载到当前shell中:

$ source myfile.config

Now you have access to the values of the variables defined inside the file:

现在您可以访问文件中定义的变量的值:

$ echo $VARIABLE
5753