Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 800
JorgeO Avatar asked Jul 02 '09 15:07

JorgeO


People also ask

Does bash script stop on error?

Bash Pitfalls Failed commands do not stop script execution In most scripting languages, if a function call fails, it may throw an exception and stop execution of the program. Bash commands do not have exceptions, but they do have exit codes.

What are two ways you can execute a shell script when you do not have execute permission for the file containing the script?

Can you execute a shell script if you do not have read permission for the file containing the script? You can give the name of the file containing the script as an argument to the shell (for example, bash scriptfile or tcsh scriptfile, where scriptfile is the name of the file containing the script).

How do I ignore a Linux error?

You can turn off failing on errors by set +e this will now ignore all errors after that line. Once you are done, and you want the script to fail again on any error, you can use set -e . After applying set +e the find does not fail the whole script anymore, when files are not found.


1 Answers

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.

like image 128
Tim Post Avatar answered Oct 20 '22 23:10

Tim Post