0

I have a tab delimited file like this:

table_a    "where id IN ($IDS)"
table_b    "where fk_id IN ($IDS)"
table_c    "where fk_id IN ($SOME_OTHER_IDS)"

And I'm trying to write a script like:

IDS="1,2,3"
SOME_OTHER_IDS="4,5,6"

while read TABLE WHERECLAUSE
do
    echo "$WHERECLAUSE"
    mysqldump ... --where="$WHERECLAUSE"
done < 'myfile.txt'

The problem is that, of course, $IDS does not get expanded/interpreted when it is read in from the read command.

It seems that I can do something in the loop like:

WHERECLAUSE=`eval echo "$WHERECLAUSE"`

But is that inherently unsafe to use eval that way?

Is there a better way to replace $IDS that avoids using eval in an unsafe manner? Preferably I'm looking for a solution that supports both OSX and Ubuntu.

Thanks!

1 Answer 1

1

eval should definitely be your last option, and particularly if the input file is user input.

For simple cases (i.e. where you don't need to worry about escape characters and quoting), you could do the following:

IDS="1,2,3"
SOME_OTHER_IDS="4,5,6"

while read TABLE WHERECLAUSE
do
    WHERECLAUSE=${WHERECLAUSE//\$IDS/$IDS}
    WHERECLAUSE=${WHERECLAUSE//\$SOME_OTHER_IDS/$SOME_OTHER_IDS}
    echo "$WHERECLAUSE"
    mysqldump ... --where="$WHERECLAUSE"   
done

Unfortunately, you do have to repeat the search-and-replace for every possible variable name, but on the positive side, that means that you control which variable names can be substituted.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .