CyberSkull
CyberSkull

Reputation: 786

How do I redirect/pipe all of my terminal shell script's output into another program from within the script?

I have a script where I want to do the equivalent of this:

myscript | anotherprogram

but from within the script. I don't want to invoke

mysubtask | anotherprogram

each time I have to run my subtasks in my script, I just want the filter started and all my OUT & ERR routed to it (the script is not interactive).

So in the end what I want to do is

  1. Set the OUT & ERR to the input of anotherprogram. anotherprogram will only run for one instance of the script so that all of my output goes to it.
  2. Run the rest of my script as normal with the OUT & ERR of my subsequent echos and subtask outputs going to anotherprogram continuously (I only want anotherprogram to run once, that is during the whole rest of my script)

Upvotes: 2

Views: 650

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

There are two simple ways I can see to achieve this. First, you could use a subshell with parentheses:

(
  echo hello
  echo world
) 2>&1 | anotherprogram

or you could use exec to redirect the various file descriptors at the top of your script

exec > >( anotherprogram ) # send stdout to anotherprogram
exec 2>&1                  # merge stderr into stdout

echo hello
echo world

Upvotes: 4

Related Questions