如果这个问题过于简洁,我很抱歉,但我试图通过Shell脚本运行MySQL查询,并希望在我的结果中查询几个不同的“列”。这一切都运行良好,但在我努力的地方,是弄清楚如何在Shell脚本中将每个“列”设置为唯一变量。这就是我所拥有的;
#!/bin/sh
results=$(mysql --host=localhost --user=root --password=root Database --skip-column-names -e 'Select cost1, cost2, cost3 from Customers';)
someMath () {
total=$1+$2+$3
echo $total
}
for cost in $results;
do
someMath $cost1 $cost2 $cost3
done
exit 0
我努力想弄清楚如何将查询结果中的所有“cost1”设置为$ cost1,查询中的所有“cost2”为$ cost2,以及所有“cost3” “在查询中是$ cost3。我的计划是将这些变量提供给另一个函数来执行其他任务。
我知道这可能很简陋,但是尽管我的搜索,我还是想不出来!谢谢!
答案 0 :(得分:0)
如果我理解正确,你需要每一行,每一列并分别传递一些其他功能。这是我写的一个例子:
#!/bin/bash
someListReceiver () {
## you know how many values you pass so you can use $1 $2...
## simple math with bc
echo "$1+$2+$3" | bc
}
someArrayReceiver () {
## Looping a received array if you don't know how many columns you'll get
declare -a arrayArguments=("${!1}")
c=0
for i in "${arrayArguments[@]}"
do
let c+=$i
done
echo $c
}
while read line
do
## IFS is your seperator, you can choose which it is, or you can use default space and us it with CONCAT_WS
IFS=$';'
for column in $line
do
## assign rows each value to an array
columnsAr+=($column)
## you can check every column with this
## echo "$column of $line"
done
## pass your row list to some function
someListReceiver ${columnsAr[@]}
## or pass your array to function
someArrayReceiver columnsAr[@]
## unset array to refill
unset columnsAr
done < <(mysql --host=localhost --user=root --password=123 test --skip-column-names -e "SELECT CONCAT_WS(';', cost1, cost2, cost3) FROM customers;")
您可以随意更改传递的数组数据。