3

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.

  • 1
    Cannot reproduce. What are you using for the client? I tried with netcat on the other end and an exit immediately ended the loop. – muru Jan 19 '17 at 14:05
  • For the client I'm using nc Raspbian 9999. Also tried using netcat, but makes no difference – ErWu Jan 19 '17 at 14:09
  • nc, netcat, to-may-to to-mah-to. – muru Jan 19 '17 at 14:13
  • Ok, was not sure if its the same command :) – ErWu Jan 19 '17 at 14:16
1

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 :

#!/bin/bash

echo "Start listening on port 12345 ..."
while read line
do
    if [ "$line" == 'exit' ]; then
        echo "Received 'exit'"
        break
    else
        echo "$line"
    fi
done < <((echo "Welcome. Please give me one of the following commands: $AVAILABLECOMMANDS") | nc -q -1 -l 12345)
echo "Good bye"
| improve this answer | |
  • Thank you. That works (but you have to pass the -l option to nc command ;)) – ErWu Jan 19 '17 at 14:33
  • Yes sorry, I'm using Fedora, and the netcat version doesn't use -q -1, and when I manually added it, I remove the -l option (don't know why). Edited ! – tobiasBora Jan 19 '17 at 14:35
2

Handy way to get incoming data and transmit data over netcat.

#!/bin/bash

netcat -l localhost 12345  # port 12345
exec 6<>/dev/tcp/localhost/12345

while read <&6
do
        echo "$REPLY"
done
| improve this answer | |
  • Why do you need a read/write on file descriptor 6 ? – abu_bua Nov 16 '18 at 21:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.