Linux – Execute a shell command from a shell script without stopping if error occurs

basherror-handlinglinux

In a sort of try/catch form I want to execute a bash that doesn't stop if an error occurs.

The specific bash is:

#!/bin/sh

invoke-rc.d tomcat stop

rm -fr /var/webapps/
cp -R $WEBAPP /var/webapps/
invoke-rc.d tomcat start

I want to exec "invoke-rc.d tomcat stop" and even if Tomcat is not running, continue to execute the other bash commands.

Best Solution

Try:

invoke-rc.d tomcat stop > /dev/null 2>&1 || true

A little background:

user@tower: # true
user@tower: # echo $?
0
user@tower: # false
user@tower: # echo $?
1

user@tower: # which true
/bin/true
user@tower: # which false
/bin/false

The real solution is looking at the tomcat init script to see how it knows if tomcat is running :) That way, you don't pester it needlessly.

See this post on the other suggestion to unset / set +e. While it would solve your immediate problem, you may find that you need the recently unset behavior in your own script, especially since you are copying files.

This is one of the biggest reasons why true and false were made, other than making Makefiles behave as expected in a variety of build environments.

Also, set +e is not entirely portable, i.e. some versions of Solaris (and even Dash) .. but I doubt that this is a concern for you.