Quantcast
Channel: How to read lines from a variable | bash - Unix & Linux Stack Exchange
Viewing all articles
Browse latest Browse all 4

Answer by Michael Homer for How to read lines from a variable | bash

$
0
0

You would be better off using process substitution rather than a variable:

while read line; do
....
done < <(grep -E 'INPUT.*ACCEPT' $FILE)

(note two < characters). This avoids loading the entire grep output into memory at once to store in a variable. The grep process will be run in parallel with the loop, and the loop will see grep's output as read's input as each line prints out (up to buffering).

This will tend to be faster and use less memory than using $(...) command substitution and keeping the whole output around. It's also generally better style if you're writing a Bash-specific script, because it's explicit about what you're using the command for.


Arguably, this is a bit of an antipattern to start with - you might be better still using an ordinary pipeline for whatever processing you require, rather than while read ... and processing it in Bash, but there are valid cases for using either.


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>