Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporarily disable 'set-e' / 'set -o errexit' in bash? [duplicate]

Tags:

linux

bash

ubuntu

I have a script that uses killall to make sure an app isn't already running before starting it:

#!/bin/bash

set -e

some_command
another_command

sudo killall myapp # this causes the script to fail if myapp isn't running
sleep 10
myapp start

However, if myapp isn't running, killall will exit the script because it returns an error.

One option to work around this is to temporarily disable set -o errexit:

#!/bin/bash

set -e

some_command
another_command

set +e
sudo killall myapp # this causes the script to fail if myapp isn't running
set -e
sleep 10
myapp start

However, the above approach is quite messy. What other options are there for temporarily disabling set -e?

like image 689
Chris Snow Avatar asked Mar 06 '15 13:03

Chris Snow


1 Answers

If you want just allow this single command to end with error and consider it normal you can:

sudo killall myapp || :

: is a noop in bash. Effectively the line above is as explicitly as possible expressing "on error do nothing". You can achieve the same effect with maybe a little more idiomatic:

sudo killall myapp || true

Of course you can also do something else like:

sudo killall myapp || echo "Failed to kill Myapp, probably it is not running at the moment." >&2
like image 84
sbarzowski Avatar answered Oct 19 '22 03:10

sbarzowski