output file only when STDERR exist.

SpongeB0B

New Member
Joined
Feb 11, 2022
Messages
26
Reaction score
7
Credits
240
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 ?
 


SlowCoder

Gold Member
Gold Supporter
Joined
May 2, 2022
Messages
265
Reaction score
200
Credits
2,168
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.
 

SlowCoder

Gold Member
Gold Supporter
Joined
May 2, 2022
Messages
265
Reaction score
200
Credits
2,168
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.
 
OP
SpongeB0B

SpongeB0B

New Member
Joined
Feb 11, 2022
Messages
26
Reaction score
7
Credits
240
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:
OP
SpongeB0B

SpongeB0B

New Member
Joined
Feb 11, 2022
Messages
26
Reaction score
7
Credits
240
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:

wizardfromoz

Administrator
Staff member
Gold Supporter
Joined
Apr 30, 2017
Messages
7,197
Reaction score
6,094
Credits
24,129
Moving this to Command Line.

Cheers

Wiz
 
$100 Digital Ocean Credit
Get a free VM to test out Linux!

Members online

No members online now.

Top