2013-02-13 84 views
0

在shell脚本中,我从数据库中检索数据并尝试打印它,但它不打印,因为我正在尝试执行此操作。从数据库中检索数据并在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值。

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

+0

哪个外壳?为什么以root用户身份登录数据库来运行查询?那是什么样的密码? – Johnsyweb 2013-02-13 12:46:54

+0

root是我为mysql数据库设置的密码以及根名称,并且没有任何错误,因为对于数据库而言,问题是使用echo语句 – shehzy 2013-02-13 13:33:05

+0

并且我使用了星号拨号计划,而我必须最终使用这些值和壳写在test3.sh文件 – shehzy 2013-02-13 13:38:24

回答

1

假设-like shell,当存在while -loop时,您正在创建的变量不存在。这是因为您正在输送结果并创建一个subshell以及一个不与父shell共享的新环境。

您可以使用process substitution将您的循环重构为for -loop。而不是尝试在变量名的末尾添加数字,请使用array

#!/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子句。但这是一个单独的问题。

+0

ok.t​​hanks很多 – shehzy 2013-02-14 07:51:50

+0

@shehzy:不客气。不要忘记[标记帮助你成为“接受”的答案](http://stackoverflow.com/faq#howtoask)。 – Johnsyweb 2013-02-14 08:11:58