Redirection. What is “<>”, “<&” and “>&-”

io-redirectionksh

<> – This operator I saw few months ago on the one site, but I don't remember what does it mean. Maybe I'm wrong and ksh has no <>.

a<&b – I know that this operator merge input stream a with output stream b. Am I right? But I don't know where I can use it. Can you get me examples?

>&- – I know nothing about it. For example, what does 2>&- mean?

Best Answer

From http://www.manpagez.com/man/1/ksh/:

   <>word        Open file word for reading and writing as  standard  out-
                 put.

   <&digit       The standard input is  duplicated  from  file  descriptor
                 digit  (see  dup(2)).   Similarly for the standard output
                 using >&digit.

   <&-           The standard input is closed.  Similarly for the standard
                 output using >&-.

You will find all those details by typing man ksh.

Especially 2>&- means: close the standard error stream, i.e. the command is no longer able to write to STDERR, which will break the standard which requires it to be writable.


To understand the concept of file descriptors, (if on a Linux system) you may have a look at /proc/*/fd (and/or /dev/fd/*):

$ ls -l /proc/self/fd
insgesamt 0
lrwx------ 1 michas users 1 18. Jan 16:52 0 -> /dev/pts/0
lrwx------ 1 michas users 1 18. Jan 16:52 1 -> /dev/pts/0
lrwx------ 1 michas users 1 18. Jan 16:52 2 -> /dev/pts/0
lr-x------ 1 michas users 1 18. Jan 16:52 3 -> /proc/2903/fd

File descriptor 0 (aka STDIN) is used per default for reading, fd 1 (aka STDOUT) is default for writing, and fd 2 (aka STDERR) is default for error messages. (fd 3 is in this case used by ls to actually read that directory.)

If you redirect stuff it might look like this:

$ ls -l /proc/self/fd 2>/dev/null </dev/zero 99<>/dev/random |cat
insgesamt 0
lr-x------ 1 michas users 1 18. Jan 16:57 0 -> /dev/zero
l-wx------ 1 michas users 1 18. Jan 16:57 1 -> pipe:[28468]
l-wx------ 1 michas users 1 18. Jan 16:57 2 -> /dev/null
lr-x------ 1 michas users 1 18. Jan 16:57 3 -> /proc/3000/fd
lrwx------ 1 michas users 1 18. Jan 16:57 99 -> /dev/random

Now the default descriptors do no longer point to your terminal but to the corresponding redirects. (As you see, you can also create new fds.)


One more example for <>:

echo -e 'line 1\nline 2\nline 3' > foo # create a new file with three lines
( # with that file redirected to fd 5
  read <&5            # read the first line
  echo "xxxxxx">&5    # override the second line
  cat <&5             # output the remaining line
) 5<>foo  # this is the actual redirection

You can do such things, but you very seldom have to do so.

Related Question