如何使用shell脚本读取属性文件

时间:2015-06-09 06:08:36

标签: linux shell

如何使用shell脚本阅读config.properties文件?

示例文件:

key1 = This is 1st value

key2 = this is 2nd value

key3
  1. 显示所有键和值。
  2. 如何检查哪个密钥没有价值?
  3. 输入显示关键相关值的任何键。

3 个答案:

答案 0 :(得分:2)

尝试以下方法:

#!/bin/bash

# Read configuration into an associative array
declare -A CONFIG
# IFS is the 'internal field separator'. In this case, your file uses '='
IFS="="
while read -r key value
do
    if [ -n $value ]; then
        CONFIG[$key]=$value
    else
        CONFIG[$key]=$value
    fi
done < YOUR_CONFIG_FILENAME
unset IFS

# If a parameter is passed, look it up by that, else print everything.
if [ $1 ]; then
    if [ -n ${CONFIG[$1]} ]; then
        echo "Key: $1, Value: ${CONFIG[$1]}"
    else
        echo "The key '$1' does not exist"
    fi
else
    for key in "${!CONFIG[@]}"; do
        if [ -n ${CONFIG[$key]} ]; then
            echo "Key: $key, Value: ${CONFIG[$key]}"
        else
            echo "Key: $key has no value"
        fi
    done
fi

exit $?

它将读取配置文件中的所有键名,并告知您是否没有为键设置值,满足您的要求(1)和(2)。

我不太了解(3)的要求是什么

&#34; 3)输入关键相关值显示的任何键&#34; 使用该要求更新脚本。

答案 1 :(得分:0)

您可以尝试一下。它也包含数据库操作:如果您清楚地了解此代码,则可以获得所需的所有答案

  #!/bin/bash
    PROPERTY_FILE=filename.properties

    function getProperty {
       PROP_KEY=$1
       PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
       echo $PROP_VALUE
    }

    echo "# Reading property from $PROPERTY_FILE"
    DB_USER=$(getProperty "db.username")
    DB_PASS=$(getProperty "db.password")
    ROOT_LOC=$(getProperty "root.location")
    echo $DB_USER
    echo $DB_PASS
    echo $ROOT_LOC
    echo "Writing on DB ... "
    mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL

    update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
    EOFMYSQL
    echo "Writing root location($ROOT_LOC) is done ... "
    counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;

    if [ "$counter" = "1" ]
    then
    echo "ROOT location updated"
    fi

答案 2 :(得分:0)

这是 (bash) script I use in my projects 的简化版本:

# reading CONFIG FILE
# usage: readConf <fileName> <several variable names>
function readConf {
local confFile=$1
shift
local allowedVars="$@" # only specified variable names will be processed
local forbidden=" #@%*()<>~'\"{}[]\$"

for VN in $allowedVars; do
    unset $VN
done

while IFS== read -r key val ; do
    var=${key//["$forbidden"]}
    if [[ " ${allowedVars[@]} " =~ " $var " ]]; then
    val=${val//["$forbidden"]}
    eval "${var}=\"${val}\""
    else
    if ! [ -z $var ]; then
        echo "conf parameter: \"$var\" is not supposed to be defined in \"$confFile\""
    fi
    fi
done < <(grep -v "^#" $confFile)
}

它扫描配置文件(第一个参数)中的指定参数(剩余参数)。某些“禁止符号”被忽略以避免代码注入。以“#”开头的行将被忽略。