"service my_service stop" is deemed an error whenever a service is in the "stopped" condition already. How to move on despite an error?

karneliy asked:

I have a bunch of bash commands that are run via ssh:


  set -e

  # ........

  service my_service stop

  # .........
  # some commands here......
  # .........

  service my_service start


ssh -t -A -q -C [email protected]$HOST "$CMD"

Sometimes, whenever my_service happens to be in the stopped status already, the command service my_service stop will return this:

--rpc-eval : RPC failed with reason :nodedown       # it's an Erlang app, hence a response
./my_script.sh: lĂ­nea 26: error: orden no encontrada

Since the said command is deemed failure, for some reason, it’ll terminate the execution, exit a session and thus won’t reach the command service my_service start.

But I want it to always run both stop and start and the commands in between, of course, regardless of the state of an app before the command service stop, and not to fail, or move on despite a possible failure after "service stop"

How to do it?

My answer:

Your script specifies set -e, which causes the shell to exit if any command in the script returns an error. If you omit this, then by default the script will continue if any command returns an error.

If you wish to keep set -e and only continue if specific commands return an error, you can make the script ignore the errors from a command by using the control operator ||, which tells the shell to execute another command if the first command fails. And then by specifying the builtin command :, which does nothing but returns successfully (similarly to the true command, which you could also use).

So for example:

service my_service stop || :

If the service command fails, then the shell will execute : which will instead return success, and the script will continue.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.