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
Use command grouping (notice the
;
on the end ofexit
).Return this on my terminal.
If you have a lot command, you can trap all errors.
This will print Oops and exit immediately, if any command on the script is failing.