在Bash中解析配置文件中的变量

Kil*_*sh9 20 variables bash awk parsing

在文件中包含以下内容:

VARIABLE1="Value1"
VARIABLE2="Value2"
VARIABLE3="Value3"
Run Code Online (Sandbox Code Playgroud)

我需要一个输出以下内容的脚本:

Content of VARIABLE1 is Value1
Content of VARIABLE2 is Value2
Content of VARIABLE3 is Value3
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

gle*_*man 59

由于您的配置文件是有效的shell脚本,因此您可以将其源代码发送到当前的shell:

. config_file
echo "Content of VARIABLE1 is $VARIABLE1"
echo "Content of VARIABLE2 is $VARIABLE2"
echo "Content of VARIABLE3 is $VARIABLE3"
Run Code Online (Sandbox Code Playgroud)

稍微干,但比较棘手

. config_file
for var in VARIABLE1 VARIABLE2 VARIABLE3; do
    echo "Content of $var is ${!var}"
done
Run Code Online (Sandbox Code Playgroud)

  • @samson一方面,它允许注入任何和所有恶意代码. (10认同)
  • 为什么要担心从配置文件中注入恶意代码?我想我可以想象这样的情况,但我需要能够从一个只存在于我的本地机器上的文件,即用户/密码组合列表... (5认同)

ant*_*nio 35

如果你需要这些......

特征

  • 单行和内联注释;
  • 修剪周围的空间=(即var = value不会失败);
  • 引用的字符串值;
  • 了解DOS行结尾;
  • 保持安全,避免采购配置文件.

shopt -s extglob
configfile="dos_or_unix" # set the actual path name of your (DOS or Unix) config file
tr -d '\r' < $configfile > $configfile.unix
while IFS='= ' read -r lhs rhs
do
    if [[ ! $lhs =~ ^\ *# && -n $lhs ]]; then
        rhs="${rhs%%\#*}"    # Del in line right comments
        rhs="${rhs%%*( )}"   # Del trailing spaces
        rhs="${rhs%\"*}"     # Del opening string quotes 
        rhs="${rhs#\"*}"     # Del closing string quotes 
        declare $lhs="$rhs"
    fi
done < $configfile.unix
Run Code Online (Sandbox Code Playgroud)

评论

tr -d '\r' ...删除DOS回车.
! $lhs =~ ^\ *#跳过单行注释并-n $lhs跳过空行.
删除尾随空格${rhs%%*( )}需要设置扩展的globbing shopt -s extglob.(除了使用sed),您可以通过更复杂的方式避免这种情况:

rhs="${rhs%"${rhs##*[^ ]}"}"  
Run Code Online (Sandbox Code Playgroud)

测试配置文件

## This is a comment 
var1=value1             # Right side comment 
var2 = value2           # Assignment with spaces 

## You can use blank lines 
var3= Unquoted String   # Outer spaces trimmed
var4= "My name is "     # Quote to avoid trimming 
var5= "\"Bob\""         
Run Code Online (Sandbox Code Playgroud)

测试代码

echo "Content of var1 is $var1"
echo "Content of var2 is $var2"
echo "Content of var3 is [$var3]"
echo "Content of var4 + var5 is: [$var4$var5]"
Run Code Online (Sandbox Code Playgroud)

结果

Content of var1 is value1
Content of var2 is value2
Content of var3 is [Unquoted String]
Content of var4 + var5 is: [My name is "Bob"]
Run Code Online (Sandbox Code Playgroud)


aba*_*asu 32

awk -F\= '{gsub(/"/,"",$2);print "Content of " $1 " is " $2}' <filename>

仅供参考,另一种纯粹的bash解决方案

IFS="="
while read -r name value
do
echo "Content of $name is ${value//\"/}"
done < filename
Run Code Online (Sandbox Code Playgroud)


alb*_*ert 8

我是这样做的

. $PATH_TO_FILE
Run Code Online (Sandbox Code Playgroud)

  • 类似于 Dave Kennedy 所说的,这允许注入任何和所有恶意代码 (2认同)
  • 仅当有人更改另一个"$ PATH_TO_FILE"中的原始文件时.如果有人可以这样做,那么系统管理员就是马虎. (2认同)