Wednesday, March 14, 2012

Ignore an error

I have a long problem when scripting the PBS script to cluster.

To stop a pipeline whenever any errors happened, we can trap it

#!/bin/bash
failclean()
{    
echo 'catched!'
exit 1
}
trap 'failclean' ERR TERM
rm -fr * 
touch b
echo 'hello,world' > 1.txt
Idonotexist
echo 'OK!'
We will get 'catched!' as output because the command 'Idonotexist' will be fail.

In the real case, the first step should be cleaning all existing file and folder to release all local disk space on each cluster node.

"rm -fr *"

However, this command may throw an error because the file permission 

"rm: cannot remove abc.txt: Permission denied"

In fact, if we can not delete other files, it is fine. We just want to use as many disk space as possible.
However, with "trap" the above command will be caught by "trap" which in turn fail your whole script.

So, our questions is: how to ignore and supress any errors when using "rm -fr *".

The solution is:

"rm -fr * 2>/dev/null || true"

Now the final demo script looks like this:

#!/bin/bash
failclean()
{    
echo 'catched!'
exit 1
}
trap 'failclean' ERR TERM
rm -fr *  2>dev/null || true
touch b
echo 'hello,world' > 1.txt
Idonotexist
echo 'OK!'





No comments:

Post a Comment