从文件描述符读取并写入标准输出

从文件描述符读取并写入标准输出

我想为每个命令在脚本的每一行输出前面添加一些内容。

我正在考虑做这样的事情:

rm foo
mkfifo foo

exec 3<>foo

cat <&3 | while read line; do
   if [[ -n "$line" ]]; then
    echo " [prepend] $line";
   fi
done &

echo "foo" >&3
echo "bar" >&3
echo "baz" >&3

基本上对于所有命令,我想在输出的每一行前面添加一些内容。我上面的代码相当伪造,但我不太知道该怎么做,它与上面类似但不完全一样。

答案1

假设脚本产生:

L1
L2

L4
L5

然后执行以下命令

script | sed 's/^\(.\+\)/ \[prepend\] \1/'

在每个非空行前面添加“ [prepend] ”:

 [prepend] L1
 [prepend] L2

 [prepend] L4
 [prepend] L5

答案2

您可能想看看DEBUGbash 中的陷阱。从man builtins

If a sigspec is DEBUG, the command arg is executed before every simple command,
for command, case command, select command, every arithmetic  for  command,  and
before  the  first  command  executes  in  a  shell function (see SHELL GRAMMAR
above).  Refer to the description of the extdebug option to the  shopt  builtin
for  details of its effect on the DEBUG trap.  If a sigspec is RETURN, the com‐
mand arg is executed each time a shell function or a script executed with the .
or source builtins finishes executing.

因此,您可以像这样设置调试功能。由于它在命令之前运行,因此您可以使用它来添加到输出之前。

#!/bin/bash

debug() {
   : # echo or other commands here
}

trap debug DEBUG

# Commands here

答案3

这个确切的代码似乎可以满足我的要求,但不确定它有多安全:

rm foo
mkfifo foo

exec 3<>foo

(
    cat <&3 | while read line; do
       if [[ -n "$line" ]]; then
        echo " [prepend] $line";
       fi
    done &
 )

echo ""  >&3;
echo ""  >&3;
echo "foo" >&3
echo "bar" >&3
echo "baz" >&3


pkill -P $$

相关内容