17

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

1 Answer 1

46

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
Sign up to request clarification or add additional context in comments.

7 Comments

Is it possible to do something like this after the original command has already been run and stored in the output variable?
I don't understand your question: I demonstrate exactly that in the first piece of code.
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 However, the script command includes everything the user sees, including ESC chars, etc, not just the stdout of previous commands.
Aside from re-running the command -- output=$(!!) -- I don't know how to programmatically capture the text that your terminal is displaying.
I am getting process: command not found when I run this on Mac.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.