无法从shell脚本中检索键值

时间:2016-12-06 04:48:55

标签: bash shell

我正在使用shell脚本从.properties文件中读取配置属性,下面是示例配置

RCTP_servername=test1
RCTP_databasename=test2
RCTP_portnumber=test3
RCTP_username=test4
RCTP_password=test5

我已经编写了一个如下所示的shell脚本,但它没有用,任何人都可以看看并指导我如何解决这个问题

#building the keys based on environment
environment=RCTP
servername_key="$environment"_servername
databasename_key="$environment"_databasename
portnumber_key="$environment"_portnumber
username_key="$environment"_username
password_key="$environment"_username

#read the config.properties files 


file=serverconfig.properties
if [ -f "$file" ]
then
 echo "$file found."

 while IFS='=' read -r key value
 do
  key=$(echo $key )
  eval "${key}='${value}'"
 done < "$file"

servername_value=${servername_key}
databasename_value=${databasename_key}
portnumber_value=${portnumber_key}
username_value=${username_key}
password_value=${password_key}
else
  echo "$file not found."
fi
echo  "$servername_value"

但是当我试图运行它时,我得到了一个,错误是./test_script_fte.sh: line 23: ${servername_key}: bad substitution

预期输出是echo $servername_value执行时test1

2 个答案:

答案 0 :(得分:1)

似乎您想使用变量的值作为另一个变量的名称。 请用以下内容替换你的最后一行

eval echo \"\$$servername_value\"

答案 1 :(得分:1)

虽然大多数时候不推荐eval,但这是一个使用indirect-reference作为

的解决方案
echo  "${!servername_value}"

我还使用逻辑中的source将逻辑调整为eval属性文件。使用完整的脚本如下。

#!/bin/bash

#building the keys based on environment

environment=RCTP
servername_key="$environment"_servername
databasename_key="$environment"_databasename
portnumber_key="$environment"_portnumber
username_key="$environment"_username
password_key="$environment"_username

#read the config.properties files 


file=serverconfig.properties

if [ -f "$file" ]
then
    echo "$file found."

    # sourcing the properties file in the current shell to fetch the values

    source "$file"

    servername_value=${servername_key}
    databasename_value=${databasename_key}
    portnumber_value=${portnumber_key}
    username_value=${username_key}
    password_value=${password_key}
else
    echo "$file not found."
fi

echo  "${!servername_value}"
echo  "${!databasename_value}"
echo  "${!portnumber_value}"
echo  "${!username_value}"
echo  "${!password_value}"