Reading properties from file and setting variable values

I want to read properties from a file and print evaluated values of each key.
I am using AIX6.1.

 
 myfile.props
protocol=http
siteA.host=siteAhostname
pageA=pageNameA
siteAURL1=${protocol}:/${siteA.host}/pagea/blabla?v1=32
siteAURL2=${protocol}:/${siteA.host}/${pageA}/blabla?v1=32
test.enc=AFSAF!$fsafasf+==
 
 evalnprint.sh
#!/bin/bash
. ./myfile.props
 
./evalnprint.sh
./abc.props: line 2: siteA.host=siteAhostname: command not found
./abc.props: line 4: ${protocol}:/${siteA.host}/pagea/blabla?v1=32: bad substitution
./abc.props: line 5: ${protocol}:/${siteA.host}/${pageA}/blabla?v1=32: bad substitution
./abc.props: line 6: test.enc=AFSAF!+==: command not found
 

Expected output

http
siteAhostname
pageNameA
http://siteAhostname/pagea/blabla?v1=32
http://siteAhostname/pageNameA/blabla?v1=32
AFSAF!$fsafasf+==

change all occurrences of siteA.hos t to siteA_host
change all occurrences of test.enc to test_enc

In other words, do not use "." as part of a variable name.

props are defined for huge real world app, I can't change existing format.
If its just keyName I would have replaced '.' with '_' and back. values have all kinds of special characters like '='

But you may be able to filter it into something you can use.

You could write a load-prop function that replaces all non-alphanumeric characters in the variable names with underscore like this:

#!/bin/bash
function load-prop {
 . <(
  awk '
    FNR==NR {
       p=index($0, "=")
       if (!p) next
       VAR=substr($0,1,p-1)
       NEW=VAR
       while (match(NEW, "[^_A-Za-z0-9]"))
          NEW=substr(NEW, 0, RSTART - 1) "_" substr(NEW, RSTART + 1)
       if(NEW != VAR) repl[VAR]=NEW
       next
    }
    {
       for(rep in repl)
          gsub(rep, repl[rep], $0)
    }
    1
' $1 $1)
}

load-prop ./myfile.props

echo "SITEAURL2 is $siteAURL2"
echo "test.enc is $test_enc"

Output:

SITEAURL2 is http:/siteAhostname/pageNameA/blabla?v1=32
test.enc is AFSAF!+==

Edit:

Just noticed that test.enc has had the string $fsafasf incorrectly expanded by the shell.
Single quotes could avoid this issue, easy if you can update your prop file(s).

The awk script could adjust for this automatically, but it needs to identify when this is needed

If all variables use the ${} format then $ characters without a following { could be used to trigger the quoting eg:

test_enc='AFSAF!$fsafasf+=='

You may also have issues with spaces within the variable values.

2 Likes

Thanks XL. I do not see single quotes in properties, I will try to wrap values in single quotes first, then use your script to expand variable substitution. Thanks for taking time to look into it.