1

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!
1
  • Your question gave me hints, but ultimately I need more. If you want to capture the result of a MySql query into an array, you can do this: stackoverflow.com/a/57061108/470749 Commented Jul 16, 2019 at 15:50

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

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.