KSH script help needed ( nice error trap routine ?)

I am running a script that runs a loop and executes a command on ${i} until the end of the for loop.

From time to time the command generates an error ( which is good) for example ERROR0005:

How can I trap the error and send an email echoing the ${i} variable in the loop and the error ?

and or better yet run a command that fixes the error based on ${i} + the error code?

This is a RH Enterprise 5.x OS using the K-Shell ( we moved from a Unix to linux environment and have hundreds of scripts to migrate so we kept the ksh format to make life easier)

Do you mean the ERR trap code?

trap 'commands go here;
       more commands;
       yet more commands; 
       echo |myscript.sh ERROR | mailx -s "error on myscript" me@mycompany.com;  
       exit 1'  ERR

The mailx statement sends email.

EVERY command that returns non-zero gets routed into the trap. Example: when you are using grep to test a string and it fails, you end up in the trap. So, you will have to have a global variable that holds the error text so the trap can ignore most harmless non-zero returns

1 Like

Thanks for the suggestion but how would that fit into a for loop?

for i in ${list}
do
command
done