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"
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"
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.
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.