我试图根据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
如您所见,由于管道,我无法在循环外获得变量的值(作为管道中的变量,基本上设置了一个不同的进程)
有任何方法可以提取循环外的实际值吗?
发布于 2015-04-23 04:26:39
如果您使用的是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"
发布于 2015-04-23 04:23:21
将其写入文件,然后在循环外读取该文件。
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)"
https://stackoverflow.com/questions/29823150
复制相似问题