Netcat implementation in bash

As a basis for a larger script I'm trying to write, I'm trying to basically implement the base netcat client in bash. My current techincally script works, it looks like this:

#!/bin/bash exec 3<>/dev/tcp/$1/$2 cat <&3 & cat <&1 >3 

The problem is that it leaves the process of the hanging cat to be killed, but I cannot determine the automatic way to do this, and the manual execution of pkill cat does not really look sporty.

+4
source share
2 answers

This is a terrible kludge, but you can spawn a subshell and something like this:

 CAT1_PID=$$ echo CAT1_PID > /tmp/CAT1_PID exec cat <&3 & 

Then, of course, you will encounter race conditions if more than one copy of this script is running.

Depending on your shell, you can call some form of exec and "rename" cat in the PS list. Then you can

 pkill the_cat_that_ate_the_network 
+3
source

I accepted Jeremy's answer as correct, but for anyone curious here the full script I ended up with:

 #!/bin/bash exec 3<>/dev/tcp/$1/$2 control_c() { kill $CAT_PID exit $? } trap control_c SIGINT cat <&3 & CAT_PID=$! cat >&3 
+4
source

All Articles