confusified
confusified

Reputation: 2330

Bash variables and outputs

grep -A 26 "some text" somefile.txt |
awk '/other text/ { gsub(/M/, " "); print $4 }' | while read line
do
   //operations resulting in a true of false answer
done

The variables declared and used in the while only exist with the sub-shell created by piping to it, how do I keep track of them from outside? I need to use the returned true or false later in the script

Upvotes: 1

Views: 69

Answers (2)

chepner
chepner

Reputation: 532418

If you are using bash 4.2 or later, set the lastpipe option. This forces the last command in a pipeline (in this case, your while loop) to run in the current shell instead of a subshell, so any modifications to variables you make in the loop remain visible after it completes.

Upvotes: 1

choroba
choroba

Reputation: 242373

Use process substitution:

while read line
do
   # operations resulting in a true of false answer
done < <(grep -A 26 "some text" somefile.txt | \
         awk '/other text/ { gsub(/M/, " "); print $4 }' )

Upvotes: 3

Related Questions