6

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?

M. Justin
  • 14,487
  • 7
  • 91
  • 130
Samraan
  • 204
  • 1
  • 2
  • 14
  • Is the layout of test.properties fixed? Lines without spaces and dots are a lot easier to handle. With a simple config you could use `. test.properties`. – Walter A Mar 24 '15 at 12:06
  • @WalterA : Yes the layout of `test.properties` is fixed – Samraan Mar 25 '15 at 04:51

3 Answers3

7

Check this, will help exactly:

expVal=`cat test.properties | grep "y.T2" | cut -d'=' -f2`
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
2

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
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • thanks for your response but there is spaces surrounding the `=` sign. Can you please suggest answer according to that... – Samraan Mar 30 '15 at 07:36
  • UUhg... That **IS** what I did `:p` I know you just misread, buy my answer does handle that case specifically. – David C. Rankin Mar 30 '15 at 07:36
  • Glad I could help. You can do almost anything you need in a shell script. Well worth taking the time to learn. Good luck. – David C. Rankin Mar 30 '15 at 07:45
2

I know this is an old question, but I just came across this and if I understand correctly, the question is to get value for a specific key from the properties file. Why not just use grep to find the key and awk to get the value?

Use grep and awk to extract the value from test.properties

export yT2=$(grep -iR "^y.T2" test.properties | awk -F "=" '{print $2}')
echo y.T2=$yT2

This value will contain space if there's one after the '='. Trim the leading whitespace

yT2="${yT2#"${yT2%%[![:space:]]*}"}"

Reference for trim: How to trim whitespace from a Bash variable?. Explanation available at reference link.

Abhimanyu Seth
  • 131
  • 1
  • 6