LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash stdout redirection (https://www.linuxquestions.org/questions/programming-9/bash-stdout-redirection-4175564017/)

danielbmartin 01-15-2016 08:02 AM

Bash stdout redirection
 
I have code in a bash shell which writes to stdout as it runs.
This is a contrived example ...
Code:

echo
echo "Program <ProgName> started."
echo
echo "Entering process stage 2."
{Many lines of code}
echo "Interim results pass the sanity test."
echo
{Many lines of code}
echo
echo "Entering process stage 3."
{Many lines of code}
echo "Everything looks good so far."
echo
echo "The finished product is ..."
{Many lines of code}
echo
echo "Program <ProgName> ended."
exit

I'd like to redirect most of stdout to a Journal file.
How is this done?

Maybe something like this ...
Code:

echo
echo "Program <ProgName> started."
echo
From now on, until further notice,
  all stdout should be written to file ABC.

echo "Entering process stage 2."
{Many lines of code}
echo "Interim results pass the sanity test."
echo
{Many lines of code}
echo
echo "Entering process stage 3."
{Many lines of code}
echo "Everything looks good so far."
echo
From now on, until further notice,
  all stdout should be written to file XYZ.

echo "The finished product is ..."
{Many lines of code}
From now on, until further notice,
  all stdout should be written to the screen (as usual).

echo
echo "Program <ProgName> ended."
exit

Daniel B. Martin

Guttorm 01-15-2016 08:13 AM

One way to do it:

Code:

echo "This goes to stdout"
(
echo "But,"
echo "These go to a file"
) > /tmp/somefile
echo "And this to stdout again"


danielbmartin 01-15-2016 08:33 AM

Quote:

Originally Posted by Guttorm (Post 5478627)
Code:

echo "This goes to stdout"
(
echo "But,"
echo "These go to a file"
) > /tmp/somefile
echo "And this to stdout again"


This surely works but requires a whole lot of code changes. I'm hoping to find a way to insert those three From now on commands, if such things exist.

Daniel B. Martin

Guttorm 01-15-2016 08:52 AM

Here is something to try:

http://unix.stackexchange.com/questi...rest-of-script

grail 01-15-2016 09:31 AM

I would use the exec option from the link above as well :) The nice part is you can put all the execs in the same piece of code and then use them when required.
On the other side of the fence, the original suggestion is actually a lot less typing and you could just use variables for the 3 file names.

sundialsvcs 01-15-2016 09:40 AM

Also, commonly, "informational" messages are written to STDERR while "output" goes to STDOUT. By default both are directed to the terminal screen.

danielbmartin 01-15-2016 02:09 PM

Quote:

Originally Posted by Guttorm (Post 5478638)

Thank you, Guttorm. This worked nicely. SOLVED!

Daniel B. Martin


All times are GMT -5. The time now is 08:52 PM.