Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With set -e, is it possible to ignore errors for certain commands? [duplicate]

Tags:

bash

shell

I have a bash script that I want to globally enable set -e.

But rather than disable it and reenable it all the time, I'm wondering if there is a way of selectively disabling error handling just sometimes. For example, commands run from systemd can be preceeded by a minus to ignore errors. Does bash has an equivalent?

e.g.

#!/bin/bash

set -e

WAN_IF=eth2

# Ignore error on next line
tc qdisc del dev ${WAN_IF} root

# I want errors to stop the script on this line
tc qdisc add dev ${WAN_IF} root handle 1: htb default 10

...
etc

Because of the need to enable/disable a lot I don't want to have to keep doing the following:

set +e
tc qdisc del dev ${WAN_IF} root

# I want errors to stop the script on this line
set -e
tc qdisc add dev ${WAN_IF} root handle 1: htb default 10
...
like image 749
hookenz Avatar asked Apr 20 '15 03:04

hookenz


People also ask

How do I ignore duplicate entries?

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

How do I ignore duplicates in SQL?

If you want the query to return only unique rows, use the keyword DISTINCT after SELECT . DISTINCT can be used to fetch unique rows from one or more columns. You need to list the columns after the DISTINCT keyword.

How do I avoid duplicates in SELECT query?

The SQL DISTINCT keyword, which we have already discussed is used in conjunction with the SELECT statement to eliminate all the duplicate records and by fetching only the unique records.

Does Count ignore duplicate values?

Yes, we can ignore duplicate rows in COUNT using DISTINCT.


1 Answers

Add || : (or anything else that is guaranteed not to fail but that's the simplest) to the end of the command.

Though many people would simply tell you that set -e isn't worth it because it isn't as useful as you might think (and causes issues like this) and manual error checking is a better policy.

(I'm not in that camp yet though the more I run into issues like this the more I think I might get there one day.)

From thatotherguy's comment explaining one of major the issues with set -e:

The problem with set -e isn't that you have to be careful about which commands you want to allow to fail. The problem is that it doesn't compose. If someone else reads this post and uses source yourfile || : to source this script while allowing failure, suddenly yourfile will no longer stop on errors anywhere. Not even on failing lines after an explicit set -e.

like image 83
Etan Reisner Avatar answered Oct 23 '22 13:10

Etan Reisner