I have a simple script which reads some lines from a connection initialized using netcat. A client can transmit some "commands". If the client write "exit" I like to close the connection.
BUT: After transmit the "exit" the script echos the "Received 'exit'" but still reads one more line before the "Good bye" appears.
echo "Start listening on port $PORT ..."
(echo "Welcome. Please give me one of the following commands:
$AVAILABLECOMMANDS") | nc -q -1 -l $PORT | while read line
do
if [ "$line" == 'exit' ]; then
echo "Received 'exit'"
break
else
result=$(executeCommand $line)
echo "$result"
fi
done
echo "Good bye"
I think I have to rewrite the loop but I have no idea how.
Can somebody help?
Thank you.
Best Answer
As explained here, bash made the choice to exit only when all the commands in the pipe as ended. Here,
netcat
does not want to stop, but after since the end pipe is broken,netcat
fails. That's why you need to wait one more time to quit the loop (by the way, you have an error when you quit the loop). Here is a version that doesn't have this pipe problem :