How to catch errors in a shell script ( multiple commands )?

Hi
I have a shell script like that

Main() {
DAY=$(date +"%d-%m-%Y")
TIME=$(date +"%T")

Command 1
Command 2
...
Command n
}

I would like to catch errors from all commands in Main() and write these errors into a file , something likes this:

Main
if < error >  
then
       echo $DAY $TIME "ERROR:" $ERROR >> error.log
else
       echo $DAY $TIME "OK" >> error.log
fi
 

and file error.log would look like this:

04-05-2015 06:00:00:OK
04-05-2015 07:00:00:OK
04-05-2015 08:00:00:ERROR : < error output ... >
04-05-2015 09:00:00:OK
04-05-2015 10:00:00:OK

Somebody help please :confused::confused::confused:

You could use $? (exit status variable) creatively and log errors. Try it out.

I know it but it seems not work with funtion, or maybe I missed something, so could you give me something more details

If you want to know the exit status of the 3rd command in a function that contains more than 3 commands, you need to capture the exit status of the 3rd command in that function in that function. You can't get the exit status of anything but the last command executed unless you saved its exit status before you ran another command.