I am facing a problem using netcat in a bash script.

I would like to match a specific output after sending a command and continue the script execution as soon as possible (not waiting for a netcat timeout)

$> echo 'my_command' | nc -q 10 <IP> <PORT> | grep -m 1 EXPECTED_OUTPUT
# ISSUE: Closes the connection quite instantly
$> echo $?
$> 1 # grep did not get (yet) the output of nc

Another try:

$> echo 'my_command' | nc -w 1 <IP> <PORT> | grep -m 1 EXPECTED_OUTPUT
Binary file (standard input) matches
# ISSUE: Wait until the timeout expires
$> echo $?
$> 0

For information:

without command, netcat prints a banner message:

$>nc <IP> <PORT>                                                                                        
welcome message

I am not against other tools (telnet, ...)

I would like a bash-compliant solution.

As the expected message should come within a second I use the timeout -w 1 of nc


You want to set it up so that nc is killed as soon as grep finishes. Here is one way:

( subshell_pid=$BASHPID ; echo 'my_command' | nc $IP $PORT > >(grep -m 1 EXPECTED_OUTPUT ; kill -13 -- -$subshell_pid ; ) )

This all runs in a subshell, and then kills all processes started by the subshell when grep finishes.

The >() is process substitution, which lets you pipe from one command to multiple commands.

  • Thank you very much for your answer and the SIGPIPE reminder; Your proposal is pretty much what I'm using. I upvoted and will accept your answer in a few days unless someone proposes something more 'straight forward' – Zermingore Feb 5 at 6:51

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.