20

What does 1>&2 mean in a bash script?

For instance, what does the following line from a bash script do?

echo "$1 is not a directory!" 1>&2

I use MacOS X. My bash script is:

if [ ! -d $1 ]; then
    echo "$1 is not a directory" 1>&2
    exit 1
fi
Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
beginner
  • 269
  • 1
  • 3
  • 6
  • 6
    "`1>&2 # Redirects stdout to stderr.`" - from [I/O Redirection](http://www.tldp.org/LDP/abs/html/io-redirection.html) – Jonny Henly Aug 04 '16 at 03:08
  • 3
    searching for `[bash] "1>&2"` shows 799 Q/As. did you bother to look before posting? Good luck. – shellter Aug 04 '16 at 03:09
  • 1
    @shellter no need to post repeated comments saying the same thing. – Robert Columbia Aug 04 '16 at 03:10
  • 2
    [`man bash`](http://man7.org/linux/man-pages/man1/bash.1.html) – Some programmer dude Aug 04 '16 at 03:11
  • 4
    Let's say you have a program that you want to capture the nicely formatted output to a log file by redirecting the output to the log (e.g. `./myscript.sh > my log` However, you also want to output error messages, but don't want them mucking up your tidy log. Since `echo` and `printf` all write to `stdout` if you do nothing to redirect the error messages, they end up in your nice tidy log file too. So, to keep them out of your log, you redirect the errors to `stderr` so they are still output (to the screen) while your normal output goes to your log. – David C. Rankin Aug 04 '16 at 03:15

1 Answers1

16

It outputs the message to stderr. Therefore 1>&2 means redirect stdout to stderr.

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
Robert Columbia
  • 6,313
  • 15
  • 32
  • 40