Suppress one expected Bash error without hiding real failures

Published · Updated

Save

Bash output and the exit status are separate. Redirect standard error for a command only when you know which diagnostic you are suppressing and still handle a failure explicitly.

Choose the narrowest redirect

The redirection 2>/dev/null discards standard error for one command. It does not change its exit status or discard standard output. For a filesystem probe, a direct test such as test -e "$path" may avoid an error message altogether.

Keep failures observable

Use an if statement to handle an expected result. For a command whose failure could mean invalid input, missing permissions or a broken dependency, send diagnostics to a bounded log and return a failure status. Test success, an expected missing item and a real failure before scheduling the script.

References

GNU Bash manual: redirection and exit status

Discuss this answer