AlwaysLearning
AlwaysLearning

Reputation: 8041

Re-direct output of command within a script whose output is re-directed

Suppose that a script of mine is invoked like this:

(script.sh 1>&2) 2>err

Is there a way to re-direct the output of one of the commands run by the script to standard output? I tried to do 2>&1 for that command, but that did not help. This answer suggests a solution for Windows command shell and re-directs to a file instead of the standard output.

For a simple example, suppose that the script is:

#!/bin/sh
# ... many commands whose output will go to `stderr`
echo aaa # command whose output needs to go to `stdout`; tried 2>&1  
# ... many commands whose output will go to `stderr`

How do I cause the output of that echo to go to stdout (a sign of that would be that it would appear on the screen) when the script is invoked as shown above?

Upvotes: 2

Views: 84

Answers (1)

123
123

Reputation: 11226

Send it to stderr in the script

echo this goes to stderr
echo so does this
echo this will end up in stdout >&2
echo more stderr

Run as

 { ./script.sh 3>&2 2>&1 1>&3 ; } 2>err

err contains

this goes to stderr
so does this
more stderr

Output to stdout

this will end up in stdout

Upvotes: 3

Related Questions