Fabricator
Fabricator

Reputation: 12772

Redirect stdout and stderr to file and stderr to stdout

The following writes stdout to a logfile and prints stderr:

bash script.sh >> out.log

This again writes both stdout and stderr to a logfile:

bash script.sh >> out.log 2>&1

How to combine both features, so that stdout and stderr are logged to a file and stderr is emailed to my inbox?

Upvotes: 2

Views: 342

Answers (4)

pacholik
pacholik

Reputation: 8972

bash script.sh 2>&1 >> out.log | tee -a out.log

First, I'm redirecting stdout to file and stderr to stdout (stdout line gets to the out.log file and stderr to pipe).

The tee command prints stdin to both stdout and file (resemblance with the letter T). Thus second, I'm printing the original stderr to both stdout and the out.log file (the -a argument means append).

Upvotes: 3

konsolebox
konsolebox

Reputation: 75488

Using process substitution you can try:

0 * * * * bash script.sh >> out.log 2> >(exec tee >(exec cat >> mail))

Or

0 * * * * bash -c 'exec bash script.sh >> out.log 2> >(exec tee >(exec cat >> mail))'

exec cat >> mail imitates mailing. Replace it with a command that actually does the mailing.

Upvotes: 0

julienc
julienc

Reputation: 20325

Here is a working solution:

./myscript.sh &> all.txt 2> stderr.txt
  • &> all.txt to have both stderr and stdout
  • 2> stderr.txt to have only stderr

And then just do whatever you want with those files, such as email logging for instance!

Upvotes: 0

anubhava
anubhava

Reputation: 785196

You can keep stdout in a separate file and stderr in separate file:

0 * * * * bash script.sh > out.log 2> err.log

and then email yourself err.log file.

Upvotes: 0

Related Questions