Skip to content
Advertisement

Unable to get the accurate value of shell variable set inside a pipe

I am trying to set a variable, based on the execution result of a MySQL statement like this:

    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

As you can see, due to pipe I am unable to get the value of the variable outside the loop (as the variable inside pipe, is basically set forking a different process)

Is there any way i can extract the actual value outside the loop?

Advertisement

Answer

What if you use a for...in instead of read, like this? :

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"
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement