0

Trying to understand how the <&3 redirect can be caught into a var in bash.

When I run the code below it stops at line 9 with the MSG to SEND being printed as if the cat <&3 is being run without catching it in the var myRcvMsg. If I open another shell and nc on the port it continues to printout each line sent (this is what I want, just need to trap it rather than print it)

If I change line to myRcvMsg="$(<&3)" then lines 10,11 execute but no var prints out.

what am I doing wrong?

thx Art

#!/bin/bash

echo "Starting Script"
exec nc -p 18000 -l &
sleep 1                                  # wait for port to open
exec 3<>/dev/tcp/192.168.1.1/18000
echo "MSG to SEND" >&3
echo "MSG has been sent"
myRcvMsg="$(cat <&3)"
echo "MSG should have been RCV'd"
echo "This is the RCV msg:${myRcvMsg}"
art vanderlay
  • 2,341
  • 4
  • 35
  • 64

2 Answers2

0

Try to read from

myRcvMsg="$(cat /dev/fd/3)"
vahid abdi
  • 9,636
  • 4
  • 29
  • 35
  • `/proc` is specific to Linux. `/dev/fd/3` should be acceptable to `bash`, regardless of what the file system actually provides. – chepner Jan 04 '14 at 17:17
  • @vanda I am using debian but get cat: /dev/fd/3: No such device or address. do I initialize it a different way before calling it? thx Art. – art vanderlay Jan 04 '14 at 22:33
  • @artvanderlay If your using linux try with `/proc/self/fd/3` in your script. – vahid abdi Jan 05 '14 at 04:23
0

The execution of nc puts it into listen mode, but it will write its output to stdout instead of echoing it back through the net. See Echo server with bash for ideas how to make it into an echo server.

On my machine I had to use 127.0.0.1 to get a connection.

Next problem is that you have to make sure that your message is not stuck in a buffer. While you wait on the out-end of &3 for nc to echo something, nc may not have actually seen your message. In my test the $(cat <&3) just hangs.

The following kind of works.

#!/bin/bash

set -x
echo "Starting Script"
exec nc -p 18000 -l -c "xargs -n1 echo" &
sleep 1                                  # wait for port to open
exec 3<>/dev/tcp/127.0.0.1/18000
cat <&3 >ttt &
sleep 1
echo "MSG to SEND" >&3
echo "MSG has been sent"
sleep 1
myRcvMsg=$(cat ttt)
echo "MSG should have been RCV'd"
echo "This is the RCV msg:\"${myRcvMsg}\""

For more information, see http://www.ict.griffith.edu.au/anthony/info/shell/co-processes.hints, where the buffering problem is highlighted in 3/ Buffered Output problem.

Community
  • 1
  • 1
Harald
  • 4,575
  • 5
  • 33
  • 72