Netcat TCP Programming with Bash Netcat TCP Programming with Bash linux linux

Netcat TCP Programming with Bash


With Bash≥4 you can use coproc:

#!/bin/bashcoproc nc { nc 10.0.0.104 4646; }while [[ $nc_PID ]] && IFS= read -r -u${nc[0]} line; do    case $line in        ('{"cmd": 1}')            printf >&${nc[1]} '%s\n' '{"error": 0}'            ;;        (*)            printf >&2 '%s\n' "Received line:" "$line"            ;;    esacdone

This avoids using temporary fifos. Without coproc, I guess the only option left is to use fifos explicitly. Here's an example:

#!/bin/bashmkfifo fifo_inwhile IFS= read -r line; do    case $line in        ('{"cmd": 1}')            printf '%s\n' '{"error": 0}'            ;;        (*)            printf >&2 '%s\n' "Received line:" "$line"            ;;    esacdone < <(nc 10.0.0.104 4646 < fifo_in) > fifo_in

For this, you'll have to manage the creation and deletion of the fifo: you'll need to create a temporary directory with mktemp, in there create the fifo, then trap your script so that on exit everything is cleaned.


/dev/tcp

If your Bash has been compiled with net redirections support, you can get rid of nc and of the fifos and coprocesses altogether:

#!/bin/bash# open TCP connection, available on file descriptor 3exec 3<> /dev/tcp/10.0.0.104/4646 || exitwhile IFS= read -r -u3 line; do    case $line in        ('{"cmd": 1}')            printf >&3 '%s\n' '{"error": 0}'            ;;        (*)            printf >&2 '%s\n' "Received line:" "$line"            ;;    esacdone

This is very likely the sweetest solution!