1

I am trying to create a function that I can pass a query into and loop through items items in chunks.

scale=10
loops=10
function runQuery (){
   loop=1
   lower=1
   upper=scale
   while [ $loop -le $loops ]; do
      echo "Loop -> $loop between $lower and $upper" 
      mysql -NB -h 127.0.0.1 -e "$query" 
      let loop=$loop+1
      let lower=lower+scale
      let upper=upper+scale
   done
}

query='delete from x where id between $lower and $upper'
runQuery

In the example above the variables are set to an empty string when the query is passed in rather than $lower and $upper being used within the function. I am guessing what I need to do is pass in a placeholder for the variable which will be defined within the function... The variables are being correctly substituted in in the echo statement but are not in the query. I could easily just put the query in the function, but I want to be able run this on multiple tables and send in different queries without having to duplicate all the looping variable set up throughout the script.

I have done quite a bit of searching for this but not sure I am searching for the right things...

BASH VERSION 3.2

Kris Davey
  • 11
  • 3
  • 1
    That was a just a typo while removing part of the echo statement from the actual code. I fixed it above and still have the same problem. – Kris Davey May 07 '19 at 16:47
  • Why don't you pass the query as a parameter? – hek2mgl May 07 '19 at 16:49
  • I just tried that by calling: replacing ```runQuery``` with ```runQuery "$query"``` and it's still not using the values for $upper and $lower in the actual query... – Kris Davey May 07 '19 at 16:57

2 Answers2

2

Parameter expansion is performed on a string just once, i.e. "$query" expands to delete from x where id between $lower and $upper and that's all, bash doesn't expand $lower and $upper.

Anyway, this is not a good idea at all, any possible workaround will make your script open to code injection.

So, if your printf support -v option, create a query template like this:

query_templ='delete from x where id between %d and %d'

and use it to generate queries:

printf -v 'query' "$query_templ" "$lower" "$upper"
mysql -NB -h 127.0.0.1 -e "$query"
oguz ismail
  • 1
  • 16
  • 47
  • 69
  • I added that and got this error: ```${query@P}: bad substitution``` I looked up this error and found a couple of articles related and tried some of the other @ options and they all failed as well... – Kris Davey May 07 '19 at 17:17
  • My prompt is actually not a $, that's part of the error... @Roadowl – Kris Davey May 07 '19 at 17:19
0
function runQuery (){
   loop=1
   lower=1
   upper=$scale
   while [ $loop -le $loops ]; do
      echo "Loop -> $loop between $lower and $upper" 
      mysql -NB -h 127.0.0.1 -e `eval echo "$query"`
      let loop=$loop+1
      let lower=lower+scale
      let upper=upper+scale
   done
}

scale=10; loops=10
query='delete from x where id between $lower and $upper'
runQuery "$query"