Operating System - HP-UX
1845825 Members
2815 Online
110250 Solutions
New Discussion

Evaluate a variable within a string

 
SOLVED
Go to solution
Sylvain CROUET
Respected Contributor

Evaluate a variable within a string

Hello.

I try to manage some logfiles' sizes with a script and a parameter file.
The parameter file contains information (separated by |) about the logfiles :
- where the logfile is,
- the maximal size I want it to be before archiving,
- etc.
The script read these information for each logfile with a 'read' command and execute the appropriate action (delete, move...).

My problem is the following : if I want to use variables within my parameter file (ex: $MY_APP_LOG), the script does not evaluate it and looks for a file named $MY_APP_LOG, which it does not find. Of course I source the adequate file before reading my parameter file (echo $MY_APP_LOG within the script works correctly).

How can I have my variables being evaluated?
4 REPLIES 4
Massimo Bianchi
Honored Contributor

Re: Evaluate a variable within a string

Hi,
try with

eval <.... all your previous string...>


this cause the evaluation of the variables.

And put the variable between parentesis, it's best.

eval .....${MY_APP_LOG}......


HTH,
Massimo

Jordan Bean
Honored Contributor

Re: Evaluate a variable within a string


Perhaps this code snippet may help.

#!/usr/bin/sh -x
while read line
do
IFS='|' eval set -- \"${line}\"
echo $@
done < paramfile

Where paramfile contains

some|pipe|delimited|text
for|one|log|file|per|line



If the parameter list is included in the script as a here-document, then this would be sufficient:

while read line
do
IFS='|' set -- $line
echo $@
done <literal|${LOGNAME}|$(logname)|literal
EOF

Sylvain CROUET
Respected Contributor

Re: Evaluate a variable within a string

Thanks for the quick answers.

Jordan, your solution works fine, but is there a simple and elegant way to affect the different fields of the line to different variables within the script?

With the first version of my script I used :
while read NAME LOCATION MAX_SIZE
do
...
done < parmfile

I do not find nothing else than keeping my loop as it is and then use your solution locally :
eval set -- ${NAME}
NAME=`echo $@`
Jordan Bean
Honored Contributor
Solution

Re: Evaluate a variable within a string

Sure thing. This should work okay.

while IFS='|' read NAME LOCATION MAX_SIZE
do
eval NAME=\"${NAME}\" LOCATION=\"${LOCATION}\" MAX_SIZE=\"${MAX_SIZE}\"
echo $NAME $LOCATION $MAX_SIZE
done < parmfile