As the basis for a larger script I'm trying to write I'm trying to basically implement a basic netcat client in bash. My current script techincally works, it looks like this:
#!/bin/bash
exec 3<>/dev/tcp/$1/$2
cat <&3 &
cat <&1 >3
The problem with it is that it leaves a hanging cat process which needs to be killed, but I can't figure an automatic way to do so, and manually running pkill cat
doesn't really seem sporting.
I've accepted Jeremy's answer as correct, but for anyone curious here's 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
It is a horrid kludge, but you could spawn a subshell and so something like this:
CAT1_PID=$$
echo CAT1_PID > /tmp/CAT1_PID
exec cat <&3 &
Then, of course, you run into race conditions if more than one copy of this script happens to be running.
Depending on your shell, you may be able to call some form of exec and "rename" cat in the PS list. Then you can
pkill the_cat_that_ate_the_network
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With