![](/img/trans.png)
[英]How to read a .properties file which contains keys that have a period character using Shell script
[英]How to read properties file using shell script
如何使用 shell 腳本讀取config.properties
文件?
示例文件:
key1 = This is 1st value
key2 = this is 2nd value
key3
請嘗試以下操作:
#!/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)的要求
“ 3)輸入與鍵有關的值顯示的任何鍵”用該要求更新腳本。
你可以試試看 它也包含數據庫操作:如果您清楚地了解此代碼,則可以獲得所需的所有答案
#!/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
# 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)
}
它掃描配置文件(第一個參數)以獲取指定參數(剩余參數)。 某些“禁止符號”被忽略以避免代碼注入。 以“#”開頭的行將被忽略。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.