rayanhacker
rayanhacker

Reputation: 23

read multiple values from a property file using bash shell script

Would like to read multiple values from a property file using a shell script

My properties files looks something like below, the reason I added it following way was to make sure, if in future more students joins I just need to add in in the properties file without changing any thing in the shell script.

student.properties

total_student=6
student_name_1="aaaa"
student_name_2="bbbb"
student_name_3="cccc"
student_name_4="dddd"
student_name_5="eeee"

When I run below script I not getting the desired output, for reading the student names from properties file

student.sh

#!/bin/bash
. /student.properties

i=1
while [ $i -lt $total_student ]
do
    {
        std_Name=$student_name_$i
        echo $std_Name

        #****** my logic *******

    } || {
        echo "ERROR..."
    }
    i=`expr $i + 1`
done

Output is something like this

1
2
3
4
5

I understand the script is not getting anything for $student_name_ hence only $i value is getting printed.

Hence, wanted to know how to read values from the properties file.

Upvotes: 2

Views: 3313

Answers (2)

helpermethod
helpermethod

Reputation: 62244

You can use indirect expansion:

std_Name=student_name_$i
echo "${!std_Name}"

the expression ${!var} basically evaluates the variable twice:

  1. first evaluation: student_name_1
  2. second evaluation: foo

Note that this is rarely a good idea and that using an array is almost always preferred.

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361889

You can do variable name interpolation with ${!foo}. If $foo is "bar", then ${!foo} gives you the value of $bar. In your code that means changing

std_Name=$student_name_$i

to

var=student_name_$i
std_Name=${!var}

Alternatively, you could store the names in an array. Then you wouldn't have to do any parsing.

student.properties

student_names=("aaaa" "bbbb" "cccc" "dddd" "eeee")

student.sh

#!/bin/bash
. /student.properties

for student_name in "${student_names[@]}"; do
    ...
done

Upvotes: 2

Related Questions