简体   繁体   English

Bash 从 stdout 获取最后一行(组合)

[英]Bash get last line (combined) from stdout

I have a script that performs many different operations and displays the status of their completion in a clear way for the user.我有一个脚本可以执行许多不同的操作,并以清晰的方式为用户显示它们的完成状态。 I need a function so that some strings can be retrieved as variables for further processing.我需要一个函数,以便可以将某些字符串作为变量检索以进行进一步处理。 This is a highly simplified example:这是一个高度简化的示例:

#!/bin/bash

echo "Test script."
echo -n "1) cat file "
cat ./testfile.f &> /dev/null
if [ $? -eq 0 ]
then
    echo "$(tput hpa $(tput cols))$(tput cub 8)[OK]"
else
    echo "$(tput hpa $(tput cols))$(tput cub 8)[FAIL]"
fi
echo -n "2) make subfolder "
mkdir ./testdir &> /dev/null
if [ $? -eq 0 ]
then
    echo "$(tput hpa $(tput cols))$(tput cub 8)[OK]"
else
    echo "$(tput hpa $(tput cols))$(tput cub 8)[FAIL]"
fi

It take some as:它需要一些:

$./test.sh
Test script.
1) cat file                               [FAIL]
2) make subfolder                         [OK]

How can I get the last line (ideally, any string) during script execution?如何在脚本执行期间获得最后一行(最好是任何字符串)? Ideally it would be using a function (so I could work with the resulting string) This string will be processed in the same script.理想情况下,它将使用一个函数(因此我可以使用结果字符串)该字符串将在同一个脚本中进行处理。 So far, I see only one solution: redirect the output of each echo command using tee.到目前为止,我只看到一种解决方案:使用 tee 重定向每个 echo 命令的输出。

Is there any way to read the already outputted data!?有没有办法读取已经输出的数据!?

Suppose that you have strings {1..5} that you need to process:假设您有需要处理的字符串 {1..5}:

process() {
   while read -r input; do
      sleep 2
      echo "Processed ${input}."
   done
}

printf "line %s\n" {1..5} | process

In this situation you might want to see the numbers before they are being processed.在这种情况下,您可能希望在处理数字之前查看这些数字。
You can do this by duplicating stdout to fd 3 and use a function.您可以通过将 stdout 复制到fd 3并使用函数来做到这一点。

display() {
   while read -r input; do
      echo "=== ${input} ===" >&3
      echo "${input}"
   done
}

process() {
   while read -r input; do
      sleep 2
      echo "Processed ${input}."
   done
}

exec 3>&1
printf "line %s\n" {1..5} | display | process

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM