2015-04-23 57 views
0

我想設置一個變量的基礎上,MySQL的聲明是這樣的執行結果:無法獲取管道內設置shell變量的準確值

errorOut=0 
    mysql -uroot -pinsite3 -rN --execute "select file_system_id from ifm.PartitionTable where physical_partition='$partName'" | while read myVal 
    do 
     echo "myVal = $myVal" 
     if [ $myVal -eq $fsId ];then 
     errorOut=1 
     echo "Found equal: errorOut = $errorOut" 
     fi 
    done 
    echo "Outside loop: errOut = $errorOut" 


Here is the output: 
myVal = 1 
myVal = 2 
Found equal: errorOut = 1 
Outside loop: errOut = 0 

正如你所看到的,由於管道我無法獲得循環外的變量的值(因爲管道內的變量,基本上設置分叉不同的過程)

有沒有什麼辦法可以提取循環外的實際值?

回答

3

如果您使用for...in而不是read,那麼該怎麼辦? :

errorOut=0 
for myVal in $(mysql -uroot -pinsite3 -rN --execute "select file_system_id from ifm.PartitionTable where physical_partition='$partName'") 
do 
    echo "myVal = $myVal" 
    if [ $myVal -eq $fsId ];then 
    errorOut=1 
    echo "Found equal: errorOut = $errorOut" 
    fi 
done 
echo "Outside loop: errOut = $errorOut" 
+0

謝謝...好:) – kingsmasher1

+0

我很高興它幫助:) – Yannoff

1

將其寫入文件,然後在循環外讀取文件。

errorOut=0 
errOutFile=Err$$.txt 
mysql -uroot -pinsite3 -rN --execute "select file_system_id from ifm.PartitionTable where physical_partition='$partName'" | while read myVal 
do 
    echo "myVal = $myVal" 
    if [ $myVal -eq $fsId ];then 
    errorOut=1 
    echo "Found equal: errorOut = $errorOut" 
    echo "$errorOut" > $errOutFile 
    fi 
done 
errorOut="$(cat $errOutFile)" 
+0

代碼可能運行在敏感的內存約束設備上,所以如果可能的話,要儘量避免使用這種方法。 – kingsmasher1

+0

啊......那麼你的意思是你根本不想寫文件,或者你不想寫大文件? – Abhay

+0

Yannoff的其他答案似乎符合你的目的。 – Abhay