Arigato Manga Arigato Manga - 4 years ago 112
Bash Question

Read command not working as expected because of While

I'm facing a weird error,

I have a file which has some inputs and based on these inputs I ask user confirmation and proceed with the actions ( as shown below ),

#!/bin/bash

func() {
cat testing | while read line
do
if [ $line = "hi" ]
then
while true
do
read -p "[y/n] : " c
case $c in
[nN] ) return 1;;
[yY] ) return 0;;
* ) echo "Enter y/Y or n/N";;
esac
done
fi
echo "HELLO !!"
done
}

func


Because of the while read line in the function, the actual read -p "[y/n] : " is picking the input from the above testing file and not from STDIN.

The program works fine if remove the cat testing | while read line loop (which is obviously not what I want).

Did anyone face this issue before or Can someone help me solve this ?

Let me know if you need any other information..

Thanks in advance..

PS: I am using MAC

Answer Source

Use a different file descriptor (and not a pipe) for testing.

while IFS= read -r line <&3; do
    ...
done 3< testing
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download