首页 > 解决方案 > 获取函数内的最后一个 echo 语句并将变量放入 bash

问题描述

我有以下 bash 脚本,在该语句中,它有几个命令和几个 echo 命令。是否可以将唯一的最后一个 echo 语句作为 return 语句并忽略所有其他 echo 命令?

#!/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 is the first statement This is the second statement The result is ok

预期输出:

The result is ok

标签: bash

解决方案


用于tail仅提取最后一行。

result=$(statement | tail -n 1)

推荐阅读