Skip to content

chaining with && or || can lead to unexpected outcomes #3503

Description

@girst

For new checks and feature suggestions

Here's a snippet or screenshot that shows a potential problem:

#!/bin/bash

exec 2>&-  # close stderr (could also happen in calling process)

[[ -z "$1" ]] && echo >&2 "missing argument" && exit 1

touch should-not-happen

this touches should-not-happen, because the exit got skipped.

a similar bug happens when condition && if-command || else-command is used to golf an if/else: if if-command fails, else-command is executed as well.

Here's what shellcheck currently says:

nothing.

Here's what I wanted to see:

chaining &&s like this can lead to unexpected outcomes if one of the intermediate processes unexpectedly exits. in the example above, i'm closing stderr before trying to write to it, causing echo to fail and the exit to get skipped.

it might be hard to detect this pattern generally, since maybe it is what the user intended (e.g. step-1 && step-2 && exit might be correct if the goal was to abort if both steps succeeded). one idea might be to check for "infallible" commands (like echo) followed by an exit or return.

the other option is of course to do nothing. then, this ticket may at least serve as a place to point to in the future.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions