0

It is difficult to find a title for this :D

I have this code:

data=( "slots" "npcs" )
for i in "${data[@]}"
do
  "$i"=$(mysql_exec "SELECT $i FROM orders WHERE order_id = $order") # slots returns 5 and npcs returns 1
done

In the loop, I want to create a variable with the name of content from $i. So it should create a variable named slots (content: 5) and npcs (content: 1)

I hope you understand my problem :P

Errors:

./install: Line 16: slots=5: command not found.
./install: Line 16: npcs=1: command not found.

2 Answers 2

3

You can use the declare command to create variable names on the fly.

data=( "slots" "npcs" )
for i in "${data[@]}"
do
  declare "$i=$(mysql_exec "SELECT $i FROM orders WHERE order_id = $order")" # slots returns 5 and npcs returns 1
done

The read command can also be used in conjunction with process substation

read $i < <(mysql_exec "SELECT $i FROM orders WHERE order_id = $order")

Consider, though, whether either approach is really superior to simply writing

grab_from_sql () {
   mysql_exec "SELECT $1 FROM orders WHERE order_id = $2"
}
slots=$(grab_from_sql slots $order)
npcs=$(grab_from_sql npcs $order)
Sign up to request clarification or add additional context in comments.

Comments

0

If you have bash 4 you can use associative arrays:

data=(slots npcs)
declare -A res
for i in "${data[@]}"; do
  res[i]=$(mysql …)
done

If you don't have a shell that supports associative arrays, you aren't going to be able to do this well using a shell. Consider using a scripting language. You can use awk, which has support for associative arrays if all else fails. Use the system function in awk to execute the mysql command.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.