linux - Assign into named variable within a shell function -
this question has answer here:
- indirect variable assignment in bash 3 answers
i have typical issue assign variable select statement, i've tried many options, none of them work..
i have function replace column name on upper(column name).
upper=(column1 column2) # array variable upper_function() { query="$1" ((i=0;i<${#upper[@]};i++)) query=$(echo "$query" | sed -e "s/\b"${upper[$i]}"\b/upper(${name[$i]})/g") done sqlquery="$query" }
below have sql statement:
sqlquery="select column1,column2 table"
now, change column1 , column2
upper(column1) , upper(column2).
so run function:
upper_function "$sqlquery"
solution above works fine, case instead of
sqlquery="$query"
i make function more automatic , assigning name of select statement variable eg below:
$2="$query"
and run function:
upper_function "$sqlquery" "sqlquery"
but not working , have no idea why, how assign variable properly? thanks
this is, @ core, bashfaq #6.
printf -v
can used indirect assignments in modern (3.1+) versions of bash:
upper=( column1 column2 ) # array variable upper_function() { local colname query=$1 varname=$2 colname in "${upper[@]}"; query=$(echo "$query" | sed -e "s/\b"${colname}"\b/upper($colname})/g") done printf -v "$varname" %s "$query" }
...thereafter:
upper_function "$sqlquery" sqlquery
on older shells, instead:
eval "$varname=\$query"
...note need trust value of $varname
not malicious, code injected variable run function. thus, never want use filename, table name, or other potentially-attacker-controlled variable name variable assigned in way.
Comments
Post a Comment