bash Shell-Script Scripting io-redirection stderr – When to Use Redirection to STDERR in Shell Scripts

bashio-redirectionscriptingshell-scriptstderr

I know that well-behaved utilities like grep output "normal" messages to stdout, and error messages to stderr.

$ grep '^foo' file1 file2
file1:foo
grep: file2: No such file or directory

When I'm writing shell scripts myself I often find it hard to decide what output and which messages I should present on stderr, or if I should bother at all.

I'd like to know about good practice: When is redirecting some message to stderr called for and reasonable, and when not?

"It depends", sure, but do you have some insights that would help me make these decisions?

In order to make this subjective question fit the format, I would like to encourage answers that address the "why", and are informed by experience and if possible backed by facts.

Best Answer

When I'm writing shell scripts myself I often find it hard to decide what output and which messages I should present on stderr, or if I should bother at all.

Silence is golden. Output nothing if everything is fine.

I'd like to know about good practice: When is redirecting some message to stderr called for and reasonable, and when not?

The easiest way to separate stderr from stdout : just imagine all your scripts output will be redirected to another command via pipe. In that case you should keep all notifications in stderr, as such unexpected information in stdout may break the pipe sequence.

Also sometimes in pipes like this one:

command1 | while read line ; do command2 ; done | command3

you need pass something from command2 to users output. The easiest way without temporary files is stderr.

Related Question