I'm trying to create a persistent connection using bash. On terminal 1, I keep a netcat running as a server:
$ nc -vlkp 3000
Listening on [0.0.0.0] (family 0, port 3000)
On terminal 2, I create a fifo and keep a cat:
$ mkfifo fifo
$ cat > fifo
On terminal 3, I make the fifo as an input to a client netcat:
$ cat fifo | nc -v localhost 3000
Connection to localhost 3000 port [tcp/*] succeeded!
On terminal 4, I send whatever I want:
$ echo command1 > fifo
$ echo command2 > fifo
$ echo command3 > fifo
Going back to terminal 1, I see the commands being received:
$ nc -vlkp 3000
Listening on [0.0.0.0] (family 0, port 3000)
Connection from [127.0.0.1] port 3000 [tcp/*] accepted (family 2, sport 41722)
command1
command2
command3
So, everything works. But when I put that in a script (I called that fifo.sh), bash is not able to write into fifo:
On terminal 1, same listening server:
$ nc -vlkp 3000
Listening on [0.0.0.0] (family 0, port 3000)
On terminal 2, I run the script:
#!/bin/bash
rm -f fifo
mkfifo fifo
cat > fifo &
pid1=$!
cat fifo | nc -v localhost 3000 &
pid2=$!
echo sending...
echo comando1 > fifo
echo comando2 > fifo
echo comando3 > fifo
kill -9 $pid1 $pid2
The output in terminal 2 is:
$ ./fifo.sh
Connection to localhost 3000 port [tcp/*] succeeded!
sending...
On terminal 1 I see only the connection. No commands:
$ nc -vlkp 3000
Listening on [0.0.0.0] (family 0, port 3000)
Connection from [127.0.0.1] port 3000 [tcp/*] accepted (family 2, sport 42191)
Connection closed, listening again.
Any idea on why it only works interactively? Or is there any other way to create a persistent connection using only Bash? I don't want to go for Expect because I have a bigger Bash script that does some work after sending the command1, and command2 depends on command1 output, etc.
Thank you!