假设我有一个包含列id, name和3行的MySQL表animals:
1, Mountain Goat
2, Angry Chicken
3, Weird Llama如果我运行命令animals=$(mysql -u root -e 'SELECT name FROM animals'),我会得到结果Mountain Goat Angry Chicken Weird Llama。
如果我将动物硬编码到数组animals=("Mountain Goat" "Angry Chicken" "Weird Llama")中,然后尝试使用命令echo ${animals[1]}访问数组的第二个条目,我得到的输出是Angry,而不是“愤怒的鸡”。
最终,我想要的是将每个值animals.name传递给BASH中的一个函数。请参阅下面的示例脚本。
#!/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并得到以下结果:
Wow, look at the Mountain Goat!
Wow, look at the Angry Chicken!
Wow, look at the Weird Llama!发布于 2016-08-31 17:25:03
问题是,当animals是一个简单的变量时,您试图(错误地)将它视为一个数组。
如果您使用bash -x运行该脚本,您将看到您正在使用所有动物作为参数调用showAnimal函数,而不是将动物逐个传递给该函数。
您所需要做的就是修复您在循环中传递给showAnimal函数的参数:
#!/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
donehttps://stackoverflow.com/questions/39236398
复制相似问题