I know this has to be something simple, but I’m just not seeing it. We have a file, SpeakerList.txt, which contains a series of single lines of a speaker in our database. new.trs holds a space-delimited version of the database. I need to verify that we find the speaker in the database, so I’m running a grep for lines that start with the speaker name. The following code always results in the if statement at the end triggering for every speaker. I’ve got a similar bit of code that checks for file existence and it works just fine. What am I missing? I know that my grep loop is running — I’ve tried it with debug echo lines. I’ve also tried printing out the $speakerFound field and verified that it is indeed blank at the end, even when I have a statement showing that it was marked “found” earlier.
for i in `cat SpeakerList.txt`
do
speakerFound=""
echo "Speaker: $i"
grep "^$i" ~/work/new.trs | while read line
do
fileName=`echo $line | cut -d' ' -f 2`
speakerFound="found"
break
done
if [ "$speakerFound" == "" ]; then
echo "$i not found in database."
fi
done
You are setting your
speakerFoundvariable in a subshell. Read this link for more details, but in general:stdinof a loop in bash, the loop will execute in a subshell.One solution is to use a file on disk to contain the result (write it in the inner loop, and read it back in when you need the result).