user1267616
user1267616

Reputation: 21

eval command function within ksh script is globbing when I don't want it to

Consider the following ksh script "myquery.ksh"

#/usr/bin/env ksh -eu

PROCESS_TYP=$1
PROCESS_DT=$2

#Generate a query
makeSQL()
{
local numfiles=0
local query='SEL \\* FROM TABLE_1_'
case "$1" in
'ABC') query="${query}ABC" ; numfiles=1 ;;
'DEF') query="${query}DEF" ; numfiles=7 ;;
esac
query="${query}_V WHERE LOAD_DT='${2}';"
printf "$query\n"
eval $3="${query}"
eval $4=$numfiles 
return 0
}

makeSQL $PROCESS_TYP $PROCESS_DT qry num_files

printf "QUERY: $qry\n"
printf "NUMFILES: $num_files\n"

In the above code, the eval $3="${query}" statement never works correctly. In all circumstances it seems to attempt to glob the "*" in the "local query="... statement.

./myquery.ksh ABC 2011-01-01

It always returns a message like this:

./myquery.ksh: line 17: \*: command not found

I am pretty sure this is my own user error with how I am applying eval in this situation but have tried nearly every alternate syntax construct for doing that eval $3 assignment but cannot manage to make this work.

I have tagged this as bash because I am pretty sure it would also behave identically there as well...

Upvotes: 1

Views: 1534

Answers (1)

Roland Illig
Roland Illig

Reputation: 41686

Did you mean:

eval "$3=\$query"
eval "$4=\$numfiles"

Explanation: in your example you want to pass variable names to the function, and these variables are then set. So the statements should look like this:

qry=$query
num_files=$numfiles

Now the question is how to put these strings together. The left hand side comes from the arguments, for example "$3". The right hand side contains a $ that must not be interpreted too early. Therefore I wrote it as \$.

I always pass a single string to the eval command, since that gives me the most reliable results. Not eval echo foo, but eval "echo foo" instead.

Alternatively you could have written:

eval "$3"='$query'
eval "$3="'$'"query"

But the first form I suggested seems the simplest to me.

Upvotes: 3

Related Questions