0

I have a comma delimited string variable that I need to remove values that are coming from standard input, which is coming in from a file. When I finish the script the values are not removed from the variable but you can tell that they were removed in the do loop. How do I update a var that is global inside the do loop of the operation?

#!/bin/bash
    varFoo="text1,text2,obit,poodle,text2,text1,doberman,bloodhound,treewalker,breaker,circuit,bum,rush"
echo text2 > /tmp/fileFeed.txt
echo circuit >> /tmp/fileFeed.txt
echo rush >> /tmp/fileFeed.txt
cat /tmp/fileFeed.txt | while read word; do
    removeWord=${varFoo//$word,/}
    removeWord=${removeWord//,$word/}
    echo ========== transaction seperator ==========
    echo word=$word
    echo removeWord=$removeWord
    varFoo=$removeWord
done
echo ^^^^^^^^^^^exiting work loop and heading to the end ^^^^^^^^^^^
echo FINAL varFoo = $varFoo
exit $?

The output is

========== transaction seperator ==========
word=text2
removeWord=text1,obit,poodle,text1,doberman,bloodhound,treewalker,breaker,circuit,bum,rush
========== transaction seperator ==========
word=circuit
removeWord=text1,obit,poodle,text1,doberman,bloodhound,treewalker,breaker,bum,rush
========== transaction seperator ==========
word=rush
removeWord=text1,obit,poodle,text1,doberman,bloodhound,treewalker,breaker,bum
^^^^^^^^^^^exiting work loop and heading to the end ^^^^^^^^^^^
FINAL varFoo =     text1,text2,obit,poodle,text2,text1,doberman,bloodhound,treewalker,breaker,circuit,bum,rush

So you'll notice that the loop removes the value from the string but when it exits the loop the variable is still at the original value before entering the loop.

Michael Jaros
  • 4,586
  • 1
  • 22
  • 39
  • Well known issue — you've got a subshell because of the pipe. A disadvantage of UUoC (Useless Use of `cat`). You could also look up `shopt -s lastpipe`. – Jonathan Leffler May 02 '15 at 05:53
  • http://mywiki.wooledge.org/BashFAQ/024 but here, an array would seem like the obvious workaround. – tripleee May 02 '15 at 05:55

1 Answers1

2

Here,

cat /tmp/fileFeed.txt | while read word; do
   ....
done

the while loop gets executed in a subshell. So the none of the variables' values will be available outside the loop. Change it to:

while read word; do
   ....
done < /tmp/fileFeed.txt

You may also be interested in reading useless use of cat.

P.P
  • 117,907
  • 20
  • 175
  • 238