Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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
like image 493
ToiletGuy Avatar asked Apr 22 '26 06:04

ToiletGuy


2 Answers

Use tail to extract just the last line.

result=$(statement | tail -n 1)
like image 125
chepner Avatar answered Apr 24 '26 22:04

chepner


You can use the builtin readarray command:

readarray -t lines < <(statement)
last_line="${lines[-1]}"
like image 24
glenn jackman Avatar answered Apr 24 '26 23:04

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!