2015-04-23 60 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