4

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
1
  • 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. Jan 26 at 14:53

1 Answer 1

9

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.