16

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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
wakey
  • 2,283
  • 4
  • 31
  • 58

1 Answers1

45

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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Is it possible to do something like this after the original command has already been run and stored in the output variable? – f1lt3r Jun 11 '15 at 16:57
  • I don't understand your question: I demonstrate exactly that in the first piece of code. – glenn jackman Jun 12 '15 at 01:53
  • 1
    Apologies, I realize I asked that in a way that made no sense. What I meant was, is it possible to capture output of commands that have already run? Ie: capture the last line of the terminal output, regardless of which command ran? The closest thing I could find to this was to use the `script` command, see: [script.html](http://www-users.cs.umn.edu/~gini/1901-07s/files/script.html) However, the `script` command includes everything the user sees, including `ESC` chars, etc, not just the stdout of previous commands. – f1lt3r Jun 12 '15 at 13:40
  • Aside from re-running the command -- `output=$(!!)` -- I don't know how to programmatically capture the text that your terminal is displaying. – glenn jackman Jun 12 '15 at 14:47
  • 3
    I am getting `process: command not found` when I run this on Mac. – Sankalp Nov 15 '17 at 04:46
  • @Sankalp use `echo` instead – Neeraj May 04 '20 at 08:54
  • how could I do the process substitution without waiting the process to end ? – Jackt Sep 17 '20 at 02:49