我有这个脚本:
#!/bin/bash
exec 4>&1
nc localhost 100 0<&4 &
echo hello
echo ....
我只想向 netcat 发送 hello 和其他内容,但这种方法行不通。 我知道
echo "hello" | nc localhost
有效,但我不需要它,"nc localhost 0<file.txt echo "hello" >file.txt
也一样。
命名管道也可以工作,但我想知道是否可以实现像上面这样简单的事情。
我建议你尝试 Bash 的协进程:
coproc nc ( netcat localhost 100 )
上述命令在后台启动
netcat
,并将其标准输入链接到文件描述符 ${nc[1]}
,并将其标准输出链接到 ${nc[0]}
。
然后您可以操作这些文件描述符以替换当前的标准输入和标准输出:
#!/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"