Score:4

How to hide output of first command when using the || operator and exit?

cn flag

This hides output from the first command, and prints Oops to stderr if it fails. So far, so good.

#!/usr/bin/env bash
invalid_command > /dev/null 2>&1 || >&2 echo "Oops"
echo hi

That outputs this:

Oops
hi

But I need to exit as well as printing a message if the first command failed. So I tried using parenthesis.

#!/usr/bin/env bash
invalid_command > /dev/null 2>&1 || ( >&2 echo "Oops" ; exit )
echo hi

Here's the output of that:

Oops
hi

But now the exit doesn't work because it's doing it in a subshell, causing it to print hi, even though I wanted the script to exit.

So, how do I get Bash to echo some text and exit if a specific command failed using the || operator? I'm aware that I can use an if one-liner to do that, but I'd prefer to not have to use a full if statement if I can avoid it.

#!/usr/bin/env bash
if [ "$(invalid_command > /dev/null 2>&1 ; printf $?)" != "0" ]; then >&2 echo 'Oops' ; exit 1; fi
cn flag
The `[` is a command that evaluates an expression and sets its own exit code appropriately, which is then consumed by the `if` statement. You can also write `if ! invalid_command >/dev/null 2>&1; then echo >&2 Oops; exit; fi`.
Score:9
sd flag

Use command grouping (notice the ; on the end of exit).

#!/usr/bin/env bash
invalid_command > /dev/null 2>&1 || { >&2 echo "Oops" ; exit; }
echo hi

Return this on my terminal.

$ ./test.sh 
Oops

If you have a lot command, you can trap all errors.

#!/usr/bin/env bash
on_error() {
    >&2 echo "Oops"
    exit 1
}
trap 'on_error' ERR
invalid_command > /dev/null 2>&1
echo hi

This will print Oops and exit immediately, if any command on the script is failing.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.