Compound indirect variable references


 
Thread Tools Search this Thread
Top Forums UNIX for Advanced & Expert Users Compound indirect variable references
# 1  
Old 08-18-2005
Compound indirect variable references

Using bash, I'm trying to read a .properties file (name=value pairs), assigning an indirect variable reference for each line in the file.

The trick is that a property's value string may contain the name of a property that occurred earlier in the file, and I want the name of the 1st property to be replaced with the value of that property.

Here's what I have so far:

###############sample.properties:###############
basePath=/home/joe
fullPath=${basePath}/data
###############End sample.properties###############

###############PropertyReader.sh###############
#! /bin/bash
declare -a settings
settings=(`cat sample.properties | tr '\n' ' '`)
for setting in "${settings[@]}"; do
echo
echo "line:"
echo ${setting}

declare -a settingString
settingString=(`echo -n ${setting/=/ }`)
eval "${settingString[0]}="'"$settingString[1]"'

echo "result:"
eval 'echo "${settingString[0]}='"${settingString[1]}"'"'
done
###############End PropertyReader.sh###############

###############output###############

line:
basePath=/home/joe
result:
basePath=/home/joe

line:
fullPath=${basePath}/data
result:
fullPath=basePath[1]/data
###############End output###############
# 2  
Old 08-18-2005
wouldn't it be easier to simply 'source' the file like so:
Code:
#! /bin/bash
. sample.properties

echo "fullPath->[${fullPath}]"

# 3  
Old 08-18-2005
If I knew the names of the properties in the file I could do that. But sample.properties is a simplified example. I actually have over 100 properties in the file I need to process, and I'd rather do it in a loop than hard-code all of my property names.
# 4  
Old 08-19-2005
Sourcing the file should work no matter how many properties there are ... can you give us an example with 3 or so properties rather than one?
# 5  
Old 08-21-2005
Hmm... i started work on something similar a while back.

It's a bit shonky as I never really had time to develop it further, but it may help. It won't do the compound variable substitution you outline, but you should be able to implement this using eval.

http://www.zazzybob.com/sh_config.html

You could probably adapt it for your needs to have variable property names instead of hard-codes as i've gone towards here.
i.e. in my script change
eval ${variable}="\"${value}\""
to
echo "${variable} = ${value}"

For the benefit of all, here's the code.... (the sample config file is on the sh_config.html page listed above)
Code:
#!/bin/ksh
#< Testing configuration file parsing with ksh
# Can parse out variable = value assignments and then
# uses eval to set shell variables as appropriate - therefore
# you must know which variables are being set so you can reference
# them later. When reading configuration files, you'd normally know
# what needs to be set and what doesn't - and you can check that these
# "pre-known" variables are set and throw errors otherwise....

CONFIG_FILE="./sh_config.conf"
i=0

# Initialise array to lines of file
while read line; do
  initial_array[${i}]="${line}"
  (( i = i + 1 ))
done < ${CONFIG_FILE}

# Set IFS to \n for processing file arrays
oldIFS=${IFS}
IFS='
'

# Comment removal ###########################################
i=0
for line in ${initial_array[@]}; do
   # Test for lines starting with '#'
   echo "${line}" | grep "^#.*$" >/dev/null 2>&1
   if [ "$?" -ne "0" ]; then
      # get rid of any inline comments
      no_comment=`echo "${line}" | sed "s/^\([^#]*\)#.*$/\1/"`
      processed_array[${i}]=${no_comment}    
      (( i = i + 1 ))
   fi
done

# Assignment validation #####################################
for line in ${processed_array[@]}; do
   echo "${line}" | egrep "^[^=]+=[^=]+$" >/dev/null 2>&1
   if [ "$?" -eq "0" ]; then
      # valid syntax
      # remove leading spaces
      first_pass=`echo ${line} |\
          sed "s/^[ 	]*\([^=]*\).*$/\1/"`
      # remove trailing spaces
      second_pass=`echo ${line} |\
          sed -e "s/[ 	]*$//" -e "s/^[^=]*=\([^=]*\)/\1/"`
      # put parts back together
      line="${first_pass}=${second_pass}"
      # remove the assignment operator
      variable=`echo ${line} |\
           sed -e "s/[ 	]*=/=/" -e "s/^\([^=]*\)=[^=]*$/\1/"`
      echo "${variable}" | grep '[[:space:]]' >/dev/null 2>&1
      if [ "$?" -eq "0" ]; then
         echo -en "WARNING: \"${variable}\" contains spaces as " >&2
         echo -en "a variable name - assignment ignored\n" >&2    
         continue
      fi
      value=`echo ${line} |\
          sed -e "s/=[ 	]*/=/" -e "s/^[^=]*=\([^=]*\)/\1/"` 
      export IFS
      eval ${variable}="\"${value}\""
   else
      :
      # invalid syntax
   fi
done

IFS=${oldIFS}

# Now we can cycle through our pre-known variables here checking them
# and acting on them as appropriate.
echo ${backup_dir}
echo ${some_var}

exit 0

EDIT: I wrote this on a Linux box, so you might need to change the echo statements as appropriate (i.e. remove the -en, add \c, etc)

Cheers
ZB

Last edited by zazzybob; 08-21-2005 at 11:00 AM..
# 6  
Old 08-21-2005
Oh, UUoC by the way

settings=(`cat sample.properties | tr '\n' ' '`)

could be slimmed down to

settings=(`tr '\n' ' ' < sample.properties `)

Cheers
ZB
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Indirect variables in Bash

Hello, I've spent hours this morning reading various past forum posts and documentation pages but I can't find exactly what I need. I'm trying to call a variable with a variable in the name without having to make a third variable. For example: path=AB legAB=50 leg$path I want to... (8 Replies)
Discussion started by: DFr0st
8 Replies

2. Shell Programming and Scripting

Refering to compound variables with a variable name

Hello, Here is my problem using KSH I have a set of compound variables, let say cmp_var1 cmp_var2 The names of these variables are stored in an indexed array. How can I access the subfields of these compound variables ? I tried: set -A cmp_varnames=(cmp_var1 cmp_var2) for cmp in... (4 Replies)
Discussion started by: luky55
4 Replies

3. Shell Programming and Scripting

Indirect variable assignment

Hi I have variable A_B=alpha also var1="A" var2="B" I want to retrieve the value alpha using var1 and var2 , somthing like echo ${${var1}_${var2}} that works. Obviously this is receiving syntax error (6 Replies)
Discussion started by: sumir
6 Replies

4. Linux

How to get an Indirect Variable Value..?

Hi, I've got a small problem. If varible A stores "B" and Variable B stores C, How to get the value of variable B by using only Variable A..? I tried the following but didnt work pease help.. $ var1=vikram $ echo $var1 vikram $ vikram=sampath $ echo $vikram sampath $ echo... (6 Replies)
Discussion started by: vickramshetty
6 Replies

5. Shell Programming and Scripting

compound variable in korn shell

in a text " Korn Shell Unix programming Manual 3° Edition" i have found this sintax to declare a compoud variable: variable=( fild1 fild1 ) but this sintax in ksh and sh (HP-UNIX) not work... why?? exist another solution for this type of variable ??? (5 Replies)
Discussion started by: ZINGARO
5 Replies

6. Shell Programming and Scripting

compound variable in korn shell

in a text " Korn Shell Unix programming Manual 3° Edition" i have found this sintax to declare a compoud variable: variable=( fild1 (0 Replies)
Discussion started by: ZINGARO
0 Replies

7. Shell Programming and Scripting

Length of an indirect variable

The construct ${#parameter} returns the number of characters in the parameter and ${!parameter} specifies an indirect variable. My question is: How do I combine these two. What I want is ${#!parameter} but this gives an error. Of course I can use: dummy=${!parameter} ${#dummy} but that's a... (0 Replies)
Discussion started by: gone_bush
0 Replies

8. Shell Programming and Scripting

Trying to use 'compound variable' in a script

Erase the space in assigment operator. array_var=`expr $base_val + $x` (1 Reply)
Discussion started by: irina
1 Replies

9. Shell Programming and Scripting

Trying to use 'compound variable' in a script

Hi there - am newish to shell scripting and would appreciate some advice on this... Am trying to use what I have seen called 'compound variables' in other langs but with no success in my shell script. This is the kind of thing I'm trying to do: base_val=123 stop=3 x=1 while do ... (3 Replies)
Discussion started by: neemic
3 Replies
Login or Register to Ask a Question