2

For example

#!/bin/bash
INT=-5
if [[ "$INT" =~ ^-?[0-9]+$ ]]; then
    echo "INT is an integer."
else
    echo "INT is not an integer." >&2
    exit 1
fi

When I delete ">&2". There is nothing different. Why do I need to add ">&2"

Braiam
  • 35,991
yuxuan
  • 219

2 Answers2

9

The difference is:

echo "INT is an integer."

writes to standard-out, and

echo "INT is not an integer." >&2

writes to standard-error.

In Unix-world, stdout is generally used when everything is working correctly and stderr is generally used to print messages when something goes wrong.

By default, stdout and stderr both print to your screen. The main difference is that the > and | operators catch stdout by default, but not stderr.

So if you had your script in the middle of a pipeline, INT is an integer. would continue down the pipeline and INT is not an integer would print to your screen instead of going into the pipeline.

1

That string merges standard out into standard error. You do that and you want to see the output on standard error. Not sure why you would think that would be necessary.

unxnut
  • 6,008
lbutlr
  • 767
  • 3
    In an ideal world, all programmers send their error messages to stderr so users can decide to hide or log them independently from regular messages. Sadly, such a world does not exist, and with most languages, many developers simply assume this is an unecessary habit. – John WH Smith Aug 14 '15 at 02:11