【问题标题】:Get the last echo statement inside a function and put inside variable in bash获取函数内的最后一个 echo 语句并将变量放入 bash
【发布时间】:2021-01-26 13:09:47
【问题描述】:

我有以下 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


    【解决方案1】:

    使用tail 仅提取最后一行。

    result=$(statement | tail -n 1)
    

    【讨论】:

    • 哇 .. 谢谢我没有意识到tail 命令的强大功能
    【解决方案2】:

    您可以使用内置的readarray 命令:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      • 2015-07-15
      • 2021-07-30
      • 1970-01-01
      相关资源
      最近更新 更多