Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get variable value from properties file in Shell Script?

Tags:

shell

unix

sh

I have a properties file test.properties and it contents are as follows:

x.T1 = 125
y.T2 = 256
z.T3 = 351

How can I assign the value of y.T2 (256) to some variable within shell script and echo this value?

like image 375
Samraan Avatar asked Feb 11 '23 14:02

Samraan


2 Answers

Check this, will help exactly:

expVal=`cat test.properties | grep "y.T2" | cut -d'=' -f2`
like image 74
Sreenivas Ponnadi Avatar answered Mar 06 '23 22:03

Sreenivas Ponnadi


You want to use read in a loop in your script. While you can source a file, it doesn't work if there are spaces surrounding the = sign. Here is a way to handle reading the file:

#!/bin/sh

# test for required input filename
if [ ! -r "$1" ]; then
    printf "error: insufficient input or file not readable.  Usage: %s property_file\n" "$0"
    exit 1
fi

# read each line into 3 variables 'name, es, value`
# (the es is just a junk variable to read the equal sign)
# test if '$name=y.T2' if so use '$value'
while read -r name es value; do
    if [ "$name" == "y.T2" ]; then
        myvalue="$value"
    fi
done < "$1"

printf "\n myvalue = %s\n\n" "$myvalue"

Output

$ sh read_prop.sh test.properties

 myvalue = 256
like image 42
David C. Rankin Avatar answered Mar 06 '23 21:03

David C. Rankin