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
You redirect stdin for the
while
loop tofile2
. So inside the loop,stdin
is redirected and aread
will read from the file, not from the terminal.With
bash
, you can easily fix that by using a different file descriptor:The
-u3
command-line flag toread
causes it to read from fd 3, while the3<file2
redirection redirects fd 3 tofile
(openingfile
for reading).Another approach to the excellent answer offered by @rici, this time not requiring bash:
Using
read <&3
reads from FD 3, just as the bash extensionread -u 3
would do.