我正在尝试根据MySQL语句的执行结果设置一个变量,如下所示:
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
正如你所看到的,由于管道,我无法在循环外得到变量的值(因为管道内的变量,基本上是设置了不同的过程)
有什么办法可以在循环外提取实际值吗?
答案 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"
答案 1 :(得分: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)"