What does >&2 mean in a shell script?

Solution 1:

File descriptor 1 is stdout and File descriptor 2 is stderr.

Using > to redirect output is the same as using 1>. This says to redirect stdout (file descriptor 1).

Normally, we redirect to a file. However, we can use >& to redirect to stdout (file descriptor 1) or stderr (file descriptor 2) instead.

Therefore, to redirect stdout (file descriptor 1) to stderr (file descriptor 2), you can use >&2.

For more information:

  • File descriptor (Computer Hope)
  • Understanding Shell Script's idiom: 2>&1 (by Brian Storti)
  • 3.6 - Redirections (GNU Bash reference manual)
  • I/O Redirection (The Linux Document Project)

Solution 2:

It is simply displaying the message "/blah/blah/: Is directory" to stderr. Also known as Standard Error which is denoted by &2.

Without the &2 messages are displayed on stdout. Also known as Standard Output which is denoted by &1.

More details on displaying messages to &>2 can be found here:

  • Bash command that prints a message on stderr
  • echo >&2 “some text” what does it mean in shell scripting

In your command posted, both messages for stdout and stderr will appear on your terminal screen. However some applications will separate the stderr messages and perform special processing.

Most people don't bother redirecting echo error messages to >&2 but it is technically the correct way of doing things.


For more reading on stdin, stdout and stderr from user or system administrator perspective see:

  • Confused about stdin, stdout and stderr?

For a programmers perspective of stdin, stdout, stderr which are &0, &1 and &2 respectively see:

  • Linux Programmer's Manual

Solution 3:

So if test -d $2 Means if $2(the second argument) is a directory, then

echo "$2: Is directory" >&2 means print $2: is directory,

and >&2 means send the output to STDERR, So it will print the message as an error on the console.


You can understand more about shell redirecting from those references:

  • https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Redirections

  • https://amrbook.com/linux/shell-script/shell-scripting-pipes-and-redirection/