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.
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.
$$ The process number of the current shell. For shell scripts, this is the process ID under which they are executing. 8. $!
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With