2

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
Dominique
  • 16,450
  • 15
  • 56
  • 112
JJK ZH
  • 21
  • 5

1 Answers1

3

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • How could this weird redirection possibly have any effect? It applies only to the `read` command, which would mean that its own stdout is fed again into its stdin. This does not make sense to me. – user1934428 Aug 10 '21 at 07:14
  • 1
    It's not using its own output. `stdout` is connected to the terminal, so it's reading from the terminal. – Barmar Aug 10 '21 at 07:15
  • 1
    When you read from the terminal you get what's typed on the keyboard. There's no looping back of output. – Barmar Aug 10 '21 at 07:17
  • It's *assuming* standard output is the terminal; that clearly may not be the case. If you redirect the script's standard output to some other file, you get a stream of "Bad file descriptor" errors, because file descriptor 1 is no longer opened for reading. – chepner Aug 10 '21 at 12:48
  • True, and so do the input prompts. I made a small edit to address the possibility of redirection. – Barmar Aug 10 '21 at 14:21