0

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
  • Your code has some typos: whileread and the closing backtick is missing. In addition, you wrote answer instead of $answer in the second conditional. Commented Mar 3, 2015 at 21:49

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.