Kiran Kiran - 5 months ago 31
Bash Question

How to read a .properties file contains keys which are having period character Using Shell script

I am trying to read properties file from shell script which contains some period character like below.

# app.properties
db.uat.user=saple user
db.uat.passwd=secret


#/bin/sh
function pause(){
read -p "$*"
}

file="./app.properties"

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

echo "User Id " $db.uat.user
echo "user password =" $db.uat.passwd
else
echo "$file not found."
fi


I have tried to parse parse the file after sourcing the file but it is not working since keys contains "." charecter and there are spaces in value also.

Please provide the solution for this. My properties file always reside in the same directory of script or somewhere in /usr/share/doc

Answer

As (Bourne) shell variables cannot contain dots you can replace them by underscores. Read every line, translate . in the key to _ and evaluate.

#/bin/sh

file="./app.properties"

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

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

  echo "User Id       = " ${db_uat_user}
  echo "user password = " ${db_uat_passwd}
else
  echo "$file not found."
fi