Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash read output?

Tags:

bash

shell

Say I execute a bash script and the output is:

Test1: Some text...
Test2: Some text...
Test3: Some text...

How would I, in the same bash script, store the above output as one or more variables?

The ideal solution would be for it to be ready to be used in a conditional like so: (line one of output would be stored in $ln1 etc.)

if [ $ln1 = "Test1: Some text..." ] ; then
like image 750
wakey Avatar asked May 02 '11 04:05

wakey


1 Answers

So you want

output=$(command)
while IFS= read -r line; do
    process "$line"
done <<< "$output"

See "Here strings" in the Bash manual.

or process substitution

while IFS= read -r line; do
    process "$line"
done < <(command)

Coming back to this after a few years, now I'd read the output of the command into an array:

readarray -t lines < <(command)
for line in "${lines[@]}"; do
    do-something-with "$line"
done
like image 159
glenn jackman Avatar answered Oct 23 '22 22:10

glenn jackman