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


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:


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.

7/2/2009 4:51:42 PM

Accepted Answer


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

A little background:

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

user@tower: # which true
user@tower: # which 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.

3/4/2010 3:35:18 AM

Disable the "exit immediately" option with set +e, run your command, then optionally re-enable it with set -e:

set +e
invoke-rc.d tomcat stop
set -e  # optional

See section 4.3.1 of the Bash manual for an explanation of the set builtin and all of its various options (of which there are many).

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow