I am trying to write a simple function to select values from a database and assign them to variables. It can have any number of arguments sent into it, and I want to assign the value retrieved to a different variable name for each argument sent in. So my code looks something like this:
function getParms {
for parm
do
`$parm`=`db2 +w -x "SELECT PARM_VALUE_TXT FROM ${FRMWRK_DB_SCHEMA}.JOB_PARM WHERE PARM_NM='$parm' WITH UR"`
done
getParms parm1 parm2 parm3
I know the db2 statement works correctly. If I just run it once and hardocde the lefthand side with a variable name and then echo it out, it is selecting the proper value from the DB and assiging it correctly. But I can't get it to assign it to the parm name I send in. Essentially I need that $parm evaluated first to the parameter name and then used as the LHS of the expression. I have tried every quoting method I know of but can't get it to work. (this is Korn shell)
function getParams {
for param in $@
do
printf -v "$param" "%s" "$(./db2 +w -x "SELECT PARM_VALUE_TXT FROM ${FRMWRK_DB_SCHEMA}.JOB_PARM WHERE PARM_NM='$param' WITH UR")"
done
}
getParams parm1 parm2 parm3
#!/bin/ksh
function getParams {
for param in $@
do
export $param="$(db2 +w -x "SELECT PARM_VALUE_TXT FROM ${FRMWRK_DB_SCHEMA}.JOB_PARM WHERE PARM_NM='$param' WITH UR")"
done
}
getParams parm1 parm2 parm3
Thank you - your solution works perfectly - does exactly what I need. But I don't understand why. I thought the "export" statement just made a local variable global to where it was called from. And in searching a bit on it that's what everything I've found says it does. So I tried removing it, thinking maybe just the way you quoted the rest of the statement is what did it, but it errors if I remove "export" from the line, and if I echo that variable even inside the function it does not assign it a value. So obviously that doesn't just change the scope, it changes how the line is evaluated. For my own knowledge, can you explain what is going on that makes this work?
Yes, there is nothing special about the export command it is just another builtin command that also happens update the value of a variable. The real issue is that variable assignments are treated specially by the shell see "Simple Command Expansion" section of the bash manual.
The main bits of concern are :
1. The words that the parser has marked as variable assignments
(those preceding the command name) and redirections are saved
for later processing.
and
4. The text after the = in each variable assignment undergoes tilde
expansion, parameter expansion, command substitution, arithmetic
expansion, and quote removal before being assigned to the vari-
able.
So you see no parameter expansion is done on the text before the = (saved at point 1.).
In contrast the text following the export builtin command gets a full set of tilde, parameter, command and arithmetic expansion: giving us our loophole.