BASH - Output - Understand the difference between standard output and standard error

A sane command writes the output that you request to standard output (stdout) and only writes errors to standard error (stderr).

For example:

dig +short A wiki.sharewiz.net
5.42.134.35
 
ip=$(dig +short A wiki.sharewiz.net)
echo "{$ip}"
{5.42.134.35}
 
ls no-such-file
ls: cannot access 'no-such-file': No such file or directory
 
output=$(ls no-such-file)
ls: cannot access 'no-such-file': No such file or directory
 
echo "{$output}"
{}

NOTE: In this example:

  • dig wrote output to stdout, which was also captured in the ip variable.
  • This was all successful.
  • ls encountered an error, so it did not write anything to stdout.
  • It wrote to stderr, which was not captured (because we 2>&1 was not used).
  • The error message appeared directly on the terminal instead.