2013-02-13 86 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