17

I'm trying to do something like

var=0  
grep "foo" bar | while read line; do  
   var=1  
done

Unfortunately this doesn't work since the pipe causes the while to run in a subshell. Is there a better way to do this? I don't need to use "read" if there's another solution.

I've looked at Bash variable scope which is similar, but I couldn't get anything that worked from it.

Community
  • 1
  • 1
swampsjohn
  • 6,826
  • 7
  • 37
  • 42

2 Answers2

25

If you really are doing something that simplistic, you don't even need the while read loop. The following would work:

VAR=0
grep "foo" bar && VAR=1
# ...

If you really do need the loop, because other things are happening in the loop, you can redirect from a <( commands ) process substitution:

VAR=0
while read line ; do
    VAR=1
    # do other stuff
done <  <(grep "foo" bar)
that other guy
  • 116,971
  • 11
  • 170
  • 194
Kaleb Pederson
  • 45,767
  • 19
  • 102
  • 147
3

then don't use pipe ,and lose the grep

var=1
while read line
do  
   case "$line" in
    *foo* ) var=1
   esac   
done <"file"
echo "var after: $var"
ghostdog74
  • 327,991
  • 56
  • 259
  • 343