Comment

Comment by thaumaturgy

The `die()` trick is good, but bash has an annoying quirk: if you try to `exit` while you're inside a subshell, then the subshell exits but the rest of the script continues. Example:

    #!/bin/bash
    
    die() { echo "$1" >&2; exit 1; }
    
    cat myfile | while read line; do
        if [[ "$line" =~ "information" ]]; then
            die "Found match"
        fi
    done
    echo "I don't want this line"
..."I don't want this line" will be printed.

You can often avoid subshells (and in this specific example, shellcheck is absolutely right to complain about UUOC, and fixing that will also fix the die-from-a-subshell problem).

But, sometimes you can't, or avoiding a subshell really complicates the script. For those occasions, you can grab the script's PID at the top of the script and then use that to kill it dead:

    #!/bin/bash
    
    MYPID=$$
    
    die() { echo "$1" >&2; kill -9 $MYPID; exit 1;  }
    
    cat myfile | while read line; do
        if [[ "$line" =~ "information" ]]; then
            die "Found match"
        fi
    done
    echo "I don't want this line"
...but, of course, there are tradeoffs here too; killing it this way is a little bit brutal, and I've found that (for reasons I don't understand) it's not entirely reliable either.
parent thaumaturgy 2 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton