0

How can I update a variable which has inside a variable and keep it global?

I know I can do this to update a variable but which isn't global:

for i in {1..24}; do 
    query=query_$i
    echo $query
done

I want to do something like this:

query=query_$i

for i in {1..24}; do
    echo $query
done

The variable doesn't update.

jevvz
  • 3
  • 2
  • 1
    Unless you're in a function and have explicitely declared your variable local, then updating its value will be visible for the whole shell the value has been updated in. I would expect a `echo $query` after your first loop to output `query_24` (see [here](https://ideone.com/nKsjRH) if not convinced), isn't that what you want? – Aaron Jan 03 '19 at 13:27
  • 2
    Would you do this in any other language? Why do you feel the need to do it in `bash`? – chepner Jan 03 '19 at 13:32

1 Answers1

0

I don't really understand why you need to do this. If it's a quiz, one way I can think is to run query as a command inside "for" loop:

query='echo query_$i'                                                                                                      

for i in {1..24}; do                                                                                                       
    eval $query                                                                                                            
done      
Kevin Cui
  • 766
  • 1
  • 6
  • 8
  • No. It isn't a quiz. It's ignorance. The need is for queries to a database where parameters change. – jevvz Jan 04 '19 at 13:11