0

在 shell 脚本中,我正在从数据库中检索数据并尝试打印它,但它没有像我尝试那样打印。

我的代码是:

 mysql -uroot -proot -Dproject_ivr_db -rN --execute "SELECT Regular FROM 
 Fee_MSc WHERE Fee_Type='Total:'" | while read value

 x=1

 do
       echo "V,FeeRegular_$y=$value"
       let "y+=1"
 done

 echo "V,fee_msc_regular="for students on regular basis admission fee 
 including other charges is $FeeRegular_1 and semester fee is $FeeRegular_2""

输出是:

 V,FeeRegular_1=12590
 V,FeeRegular_2=12850

 V,fee_msc_regular=for students on regular basis admission fee including other
 charges is and semester fee is   

它不会在字符串输出中打印$FeeRegular_1和的值。$FeeRegular_2

如何在输出字符串中获取这些变量的值?

4

1 回答 1

1

假设一个类似while的 shell,当-loop 存在时,您要创建的变量不存在。这是因为您正在管道传输结果并创建具有新环境的子 shell,该环境不与父 shell 共享。

您可以for使用流程替换将循环重组为 - 循环。与其尝试将数字附加到变量名称的末尾,不如使用数组

#!/bin/bash
i=0
for value in $(mysql -u{$db_user} -p${db_pass} -D${db_name} -rN --execute "
    SELECT Regular FROM Fee_MSc WHERE Fee_Type='Total:' ")
do
    FeeRegular[$i]=${value}
    echo "FeeRegular[$i]=${FeeRegular[$i]}"
    let "i+=1"
done
echo "Found ${#FeeRegular[@]} fees..."
echo "For students on regular basis admission fee including other charges is
${FeeRegular[1]} and semester fee is ${FeeRegular[2]}."

我还建议不要使用 root 帐户来查询数据库、增加密码强度并且不要发布它们

现在...您确定要查找的结果在第 1 行和第 2 行吗?您order by在查询中没有指定子句。但这是一个单独的问题。

于 2013-02-13T20:23:37.400 回答