Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set -e and short tests

Tags:

When I was new to shell scripting, I used a lot of short tests instead of if statements, like false && true.

Then later I learned using set -e, and found my scripts were dying for some reason, and they would work if I replaced the short tests with full if statements. Now, the time has gone, and I still use full if statements only.

The most interesting is that if I open an interactive shell and do the following:

set -e false && true echo $? 

it returns 1 but the shell doesn't die!

I see that I have been wasting too many lines of code. Anyone could explain to me how can I use set -e with short tests safely, eg. without the script dying?

like image 308
Teresa e Junior Avatar asked Aug 03 '11 17:08

Teresa e Junior


People also ask

What is a test set?

A test set is a portion of a data set used in data mining to assess the likely future performance of a single prediction or classification model that has been selected from among competing models, based on its performance with the validation set.

What is minimum test set?

A minimal set of test cases is generated as an indicator to the effectiveness of the change. Initial results show that the method is applicable for quick testing to ensure that basic functionality works correctly.

What is test set used for?

– Test set: A set of examples used only to assess the performance of a fully-specified classifier. These are the recommended definitions and usages of the terms.


1 Answers

The Single UNIX Specification describes the effect of set -e as:

When this option is on, if a simple command fails for any of the reasons listed in Consequences of Shell Errors or returns an exit status value >0, and is not part of the compound list following a while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit.

As you see, a failing command in an AND list will not make the shell exit.

Using set -e

Starting shell scripts with set -e is considered a best practice, since it is usually safer to abort the script if some error occurs. If a command may fail harmlessly, I usually append || true to it.

Here is a simple example:

#!/bin/sh set -e  # [...] # remove old backup files; do not fail if none exist rm *~ *.bak || true 
like image 130
Danilo Piazzalunga Avatar answered Oct 15 '22 14:10

Danilo Piazzalunga