Skip to content

Files

Latest commit

 

History

History
42 lines (27 loc) · 1.04 KB

SC2251.md

File metadata and controls

42 lines (27 loc) · 1.04 KB

Pattern: Ineffectual ! in front of command

Issue: -

Description

Command inverted with ! may have no effect. In particular, it does not appear as a condition in an if statement or while loop, or as the final command in a script or function.

The most common reason for this is thinking that it'll trigger set -e aka errexit if a command succeeds, as in the example. This is not the case: ! will inhibit errexit both on success and failure of the inverted command.

Using && exit will instead exit when failure when the command succeeds.

Example of incorrect code:

set -e
! false

Example of correct code:

set -e
! false && exit 1

Exceptions

ShellCheck will not detect cases where $? is implicitly or explicitly used to check the value afterwards:

set -e;
check_success() { [ $? -eq 0 ] || exit 1; }
! false; check_success
! true; check_success

In this case, you can ignore the warning.

Further Reading