Variable in while loop being read from unexpected

2019-08-28 21:30发布

问题:

I am trying to compare the content of file2 with that of file1 and based on that I need to take some action.

But when I try to take input from user (in variable answer) whether to start or not, the program does not wait for user input and takes value assigned to variable line automatically.

#!/bin/bash

while read line;
do 
var=`grep $line file1.txt`

if [ -z "$var"] 
then 
    echo "$line is not running"
    echo "Do you want to start? (Y/N)"
    read answer
    if [ "$answer" = 'Y' ] || [ "$answer" = 'N' ]
    then
        if [ "$answer" = 'Y' ]
        then
        (some action)
        else
        (action)
        fi
    else
    (action)
    fi
fi

done < file2

回答1:

You redirect stdin for the while loop to file2. So inside the loop, stdin is redirected and a read will read from the file, not from the terminal.

With bash, you can easily fix that by using a different file descriptor:

while read -r -u3 line; do
  echo "$line"
  read -p "Continue? " yesno
  if [[ $yesno != [Yy]* ]]; then break; fi
done 3<file2

The -u3 command-line flag to read causes it to read from fd 3, while the 3<file2 redirection redirects fd 3 to file (opening file for reading).



回答2:

Another approach to the excellent answer offered by @rici, this time not requiring bash:

while read -r line <&3; do
  echo "$line"
  printf "Continue? " >&2
  read yesno
  case $yesno in
    [Yy]*) : ;;
    *) break ;;
  esac
done 3<file2

Using read <&3 reads from FD 3, just as the bash extension read -u 3 would do.



标签: bash shell unix