OnlyDean
OnlyDean

Reputation: 1039

Use MySQL output as input for BASH function in a loop

Let's say I have a MySQL table animals with columns id, name and 3 rows:

1, Mountain Goat
2, Angry Chicken
3, Weird Llama

If I run the command animals=$(mysql -u root -e 'SELECT name FROM animals'), I get the result Mountain Goat Angry Chicken Weird Llama.

If I hard code the animals into the array animals=("Mountain Goat" "Angry Chicken" "Weird Llama"), and then try to access the second entry of the array with the command echo ${animals[1]}, I get the output Angry, not "Angry Chicken".

Ultimately what I want is the pass each value animals.name into a function in BASH. See the sample script below.

#!/bin/bash
animals=$(mysql -u root -e 'SELECT name FROM animals')
function showAnimal {
    echo "Wow, look at the "$1"!";
}
for i in $animals; do
    showAnimal ${animals[$i]}
done
showAnimal

And get the following results:

Wow, look at the Mountain Goat!
Wow, look at the Angry Chicken!
Wow, look at the Weird Llama!

Upvotes: 1

Views: 489

Answers (1)

Jiri Valenta
Jiri Valenta

Reputation: 540

The problem is that you're trying to (incorrectly) treat animals as an array when it is a simple variable.

If you run the script with bash -x you will see that you are calling the showAnimal function with all of the animals as parameters, instead of passing the animals to the function one by one.

All you need to do is to fix the parameter you pass to the showAnimal function in your loop:

#!/bin/bash
animals=$(mysql -u root -e 'SELECT name FROM animals')
function showAnimal {
    echo "Wow, look at the "$1"!";
}
for i in $animals; do
    showAnimal $i
done

Upvotes: 2

Related Questions