0

Let's say I have two scripts, one calls the other, how can I prepend text to each echo to visually indicate the echo comes from the called command?

a.sh

#!/usr/bin/env sh
echo - BEGIN
./b.sh # Append "-" to each echo?
echo - END

b.sh

#!/usr/bin/env sh
echo - BEGIN
echo - END

Output I want:

- BEGIN
-- BEGIN
-- END
- END

I can't touch b.sh and I need to stream the output.

  • 1
    What if b.sh contained a command other than echo and the command generated output? In general do you want the whole output from b.sh to be modified? or just output from echos? – Kamil Maciorowski Mar 16 '23 at 19:43

2 Answers2

4

If it's just text output by the echo command that you want prepended with a -, you could redefine echo as a function and source the other script with the . special builtin so it inherits that function:

#!/usr/bin/env sh
printf '%s\n' '- BEGIN'
echo() {
  printf %s -
  command echo "$@"
}
. ./b.sh
printf '%s\n' '- END'

(note that in any case echo is best avoided)

2

If you mean you want to add this to all output printed by the second script, just pipe its output to sed. In your example, make a.sh like this:

#!/usr/bin/env sh
echo - BEGIN
./b.sh | sed 's/^/-/' 
echo - END

This results in:

$ a.sh
- BEGIN
-- BEGIN
-- END
- END
terdon
  • 242,166