[BASH] redirect standard error and use it inside

Hi all,

Maybe my question is too simple but till now i couldn't figure about a solution :frowning:

I have a bash script scheduled in cron:
<cron time parameters> my_script.sh > result.log 2>&1

By this way i can have standard output and standard error in my result.log file

Now i want my script to alert me when some critical errors occurs.
For example, if i want to do a check like that:
ls $dir
if [ $? -ne 0 ]
then
echo "ALERT ALERT ALERT" >>fileAlert.log
fi

But as i redirected the stderror i can't catch it enymore with $?, isn't it?

When i launch the script, by commmand line:
my_script.sh > results.log 2>&1

i get the error:
"Ambiguous output redirect"

I can do something about that? Or maybe i miss something else?

For sure i can use AWK and similiar to parse output of each test in the script, but i would like to use the exit status of each command.
Is it possible??

thanks in advance! :slight_smile:

In my testing:

myscript contains:
ls -al bonehead
touch tmptest

Issuing the command:
./myscript > temp2test.log 2>&1
This writes the error for the nonexistent bonehead file and touches the tmptest file but returns 0 for echo $?

Changing myscript to contain an exit status at the end:
ls -al bonehead
touch tmptest
exit 231

This writes the error for the nonexistent bonehead file and touches the tmptest file, but returns 231 for echo $?

So, you can track the conditions of each command you need error notification on, and assign a "meaningful" exit status to a variable, then at the end of your script, exit "$somevariablename".

You could combine multiple error status values to the same variable for exit status that can be grep'd for major issue notification...

So exit status will need to be handled in the script somehow (as it really should be).

<edit> OR, just grep yer log file for the error messages you expect to receive notification on.

Thank you Flying_Meat :slight_smile:

I'm trying to do like you suggest in my scripts...

But, there isn't in your opinion a way to simply duplicate the standard error?
To let have it "as a copy" in the logfile when the sript is lauched, and still can use it inside the script.
Something like the tee command do for standard output.