What '<&1' mean in this script "read -n 1 k <&1"

Viewed 128

New to shell script.

I know 'read' is used to read user input, and '-n' is the number of characters waiting for, 'k' is the variable name to store reply. What is '<&1' used for?

Here is the whole script:

#!/bin/bash
echo "Press 'q' to exit"
count=0
while : ; do
  read -n 1 k <&1
  if [[ $k = q ]] ; then
    printf "\nQuitting from the program\n"
    break
  else
    ((count=$count+1))
    printf "\nIterate for $count times\n"
    echo "Press 'q' to exit"
  fi
done
1 Answers

From the bash manual

[n]<&word
is used to duplicate input file descriptors. If word expands to one or more digits, the file descriptor denoted by n is made to be a copy of that file descriptor. If the digits in word do not specify a file descriptor open for input, a redirection error occurs. If word evaluates to ‘-’, file descriptor n is closed. If n is not specified, the standard input (file descriptor 0) is used.

So this is reading from file descriptor 1, which is standard output, instead of reading from the normal standard input.

It's not clear why this script is doing that. It might be used when standard input is already redirected elsewhere, as in "Press enter" while in a bash pipe, but that doesn't seem to be the case in this script (unless input of the script itself is redirected). Although if you want to read from the terminal, </dev/tty is a better way to do it, in case standard output is also redirected.

Related