在 unix shell 脚本中从 app.properties 读取带有 '=' 和空格的属性

read properties with '=' and white spaces from app.properties in unix shell script

我正在阅读如下所示的属性,但因为我使用的是 = 符号,所以它正在中断。如何阅读完整的 属性? 在 属性 文件中 dbName=jdbc://sample:8080;nameSpace=name1; --config host=sample

# Script used to read Property File
FILE_NAME=Test.prop
# Key in Property File
key="dbName"

# Variable to hold the Property Value
prop_value=""

getProperty()
{
        prop_key=
        prop_value=`cat ${FILE_NAME} | grep ${prop_key} | cut -d'=' -f2`
}

getProperty ${key}
echo "Key = ${key} ; Value = " ${prop_value}

只需删除第一个 = 之前的所有文本。

prop_value=$(grep "^${prop_key}=" ${FILE_NAME} | sed 's/[^=]*=//')

备注:
输入文件很少需要 cat。我修改了 grep 模式以仅匹配行开头的完整键。这避免了匹配可能包含指定键作为键或值的子字符串的行。我用 $(...).

替换了反引号