Redirect stdinput of netcat to current stdout of bash script

84 Views Asked by At

i have this script:

#!/bin/bash
exec 4>&1
nc localhost 100 0<&4 &
echo hello 
echo ....

I just want to send hello and other things to netcat but that approach doesn't work. I know echo "hello" | nc localhost works but i don't need it, same for "nc localhost 0<file.txt echo "hello" >file.txt. Named pipe also work, but i'd want to know if something easy like above can be achieved.

1

There are 1 best solutions below

0
xhienne On BEST ANSWER

I suggest you try Bash's coprocesses:

coproc nc ( netcat localhost 100 )

The above command starts netcat in the background and links its standard input to file descriptor ${nc[1]} and its standard output to ${nc[0]}.

You can then manipulate those file descriptors in order to replace your current stdin and stdout:

#!/bin/bash
coproc nc ( netcat localhost 100 )

# Current stdin and stdout are saved in old_stdin and old_stdout,
# then they are replaced with the input and output of the coprocess
exec {old_stdin}<&0 {old_stdout}>&1 <&${nc[0]} >&${nc[1]}

echo "This is sent to netcat"
read reply

# We restore the former stdin and stdout
exec <&$old_stdin >&$old_stdout
echo "This was received from netcat: $reply"