output file only when STDERR exist.

SpongeB0B

Member
Joined
Feb 11, 2022
Messages
30
Reaction score
7
Credits
270
Hi everyone,

I created a cron job trough crontab -e and it work

line in the crontab :
Bash:
* * * * * myscript.sh 2>>/home/me/Desktop/errors.txt

But I have a small bug, every-time it run, it generate the errors.txt (nothing inside)
is there a way to generate this file only if indeed there is an error ? and not at each run ?

Thanks


BTW, I hope that my title was explicit enough ?
 


I would recommend a different path. Output both STDOUT and STDERR to the file. Standard output can add context to errors, especially if the errors aren't particularly verbose.

Also, you might find 'tee' to be a valuable command in your use case.
 
Thank you @SlowCoder how can I "export" both STDOUT and STDERR ?

Do you have any example with tee ?
This should do it:
Code:
[command] 2>&1 | tee [output.txt]
All output will be both displayed in terminal and send to output file.
Example:
Code:
sudo apt update 2>&1 | tee aptoutput.txt
Note: use tee -a to append output, otherwise it overwrites.
 
I've tested the solution of @SlowCoder
Bash:
[command] 2>&1 | tee [output.txt]

and indeed it's work if you want both STDOUT and STDERR.

But in my case is not what I'm looking for...

I want only the STDERR to be write to a file if there is an error.

In my case with
Bash:
2>>/thefile.txt
thefile.txt is created (empty) even if there is no error :/
I would like that this file if only created if there is an error.

Any ideas ?
 
Last edited:
If it help someone I done this ( until a better solution)

Bash:
* * * * * myscript.sh 2>>/errors.txt && [ -s /errors.txt ] || rm -rf /errors.txt

I use a different path for error, it's to make a shorter example.
 
Last edited:
Moving this to Command Line.

Cheers

Wiz
 

Members online


Latest posts

Top