jeudi 10 septembre 2020

Bash: if conditional clause while iterating over a 2-dimensional properties file

I have a data structure defined by item[i] -- contains -- > subitem[k]. I want to write a small bash script which parses subitems and items executes an action on hitting a specific subitem.

My sampletext.properties file is as such:

Item1.subitem1=tom
Item1.subitem2=bob
Item2.subitem1=alice

Overcoming the absence of 2-dimensional arrays in Bash, I wrote two functions, one for getting the value of a key and one for counting the occurrences of a string.

I then build a for loop for parsing the items and I try to include a IF-clause to hit "bob" and say something. Unfortunately, the script is not seeing bob and it seems like the IF-clause is not working:

#!/bin/bash

# The input text file 
PROPERTY_FILE=sampletext.properties

#Defining a function to get the value of a key
function getProperty {
   PROP_KEY=$1
   PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2 | tr -d '\n'`
   echo $PROP_VALUE
}

# Counting the number of subitem1 entries
function countsubitem1 {
  toolsnumber=`cat $PROPERTY_FILE | grep "Item[0-9].subitem1" | wc -l`
  echo $toolsnumber
}
countsubitem1


for (( i=1; i<=$(countsubitem1); i++))
do
  subitem1=`getProperty "Item$i.subitem1"`
  subitem2=`getProperty "Item$i.subitem2"`
  echo item$i:$(getProperty "Item$i.subitem1") # Testing the getProperty function again
  echo subitem2:$subitem2 # Testing the for loop and the getProperty function
  if [[ "$subitem2" == "bob" ]]; then
    echo "I see bob!"
  else
    echo "No bob here!"
  fi  
done

What I get launching the script:

2
item1:tom
subitem2:bob
No bob here!
item2:alice
subitem2:
No bob here!

What I expect:

./samplebash.sh
2
bob
item1:tom
I see bob!

item2:alice
No bob here!

I tried several alterations of the IF-clause:

 if [ "$subitem2" == "bob" ]; then
  if [ '$subitem2' == 'bob' ]; then

but I always get the 'No bob here!' message.

Aucun commentaire:

Enregistrer un commentaire