0

I want to prepend something to each line of output in a script, for every command.

I was thinking of doing something like this:

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

basically for all commands I want to prepend something to each line of the output. My code above is fairly bogus, but I don't quite know how to do it, it's something like the above but not quite.

1

Assuming script produces:

L1
L2

L4
L5

then the following command

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

prepends " [prepend] " to each non-empty line:

 [prepend] L1
 [prepend] L2

 [prepend] L4
 [prepend] L5
1

You may want to look at the DEBUG trap in bash. From 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.

So, you could set up a debug function like this. Since it runs before commands you could use it to prepend to your output.

#!/bin/bash

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

trap debug DEBUG

# Commands here
0

This exact code seems to do what I want, but not sure how safe it is:

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 $$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.