Get the last echo statement inside a function and put inside variable in bash

Viewed 516

I have the following bash script, inside that statement, it has several commands with few echo commands. Is it possible to get the only last echo statement as return statement and ignore all other echo commands?

#!/bin/bash

function statement(){

echo "This is the first statement"
echo "This is the second statement"
# do something else
echo "The result is ok"  # I want to display only this in my output.
}


last_echo=$(echo $(statement))

echo "${last_echo}"

This will output every statement:

This is the first statement This is the second statement The result is ok

Expected output:

The result is ok
2 Answers

Use tail to extract just the last line.

result=$(statement | tail -n 1)

You can use the builtin readarray command:

readarray -t lines < <(statement)
last_line="${lines[-1]}"
Related