Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple lines in bash without spawning a new subshell?

Tags:

bash

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.

like image 356
swampsjohn Avatar asked Mar 04 '10 00:03

swampsjohn


People also ask

How do I run multiple lines in bash?

Using a Backslash. The backslash (\) is an escape character that instructs the shell not to interpret the next character. If the next character is a newline, the shell will read the statement as not having reached its end. This allows a statement to span multiple lines.

What is $$ in shell script?

$$ The process number of the current shell. For shell scripts, this is the process ID under which they are executing. 8. $!

Does piping create a subshell?

Pipelines create subshells. Changes in the while loop do not effect the variables in the outer part of the script, as the while loop is run in a subshell. Such a rearrangement might not be appropriate for your problem, in which case you'll have to find other techniques.

How do I type multiple lines in terminal?

To enter multiple lines before running any of them, use Shift+Enter or Shift+Return after typing a line. This is useful, for example, when entering a set of statements containing keywords, such as if ... end.


1 Answers

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)
like image 193
Kaleb Pederson Avatar answered Sep 28 '22 18:09

Kaleb Pederson