0

I don't understand how to properly setup a data transmission between two host with unstable ethernet connection.

This is my /simple/bash/script.sh

#!/bin/bash


while [ true ]; do
    cat /dev/virtual  | nc -v 192.168.1.1 5005 || echo "nc failed" && exit   
    sleep 5s
done

exit

If I manually start it and on the destination netcat isn't running it would say:

5005 (tcp) failed: Connection refused

But it would not exit.

I need it the other way:

  1. check netcat connection is ok.
  2. then pipe cat /dev/virtual.

Is there a way to catch the netcat status and then if it is failed: connection refused restart the main bash script?

5
  • I'm sorry, I'm trying to understand but I'm not able to. What you want to do is "until netcat doesn't accept the connection, wait. When nc is okay, send /dev/virtual via netcat"? Jun 4, 2020 at 12:26
  • Yes Francesco, you've explained it better than me. That is what I would like to do.
    – user340971
    Jun 4, 2020 at 12:42
  • Why restart the script if the only code is in a loop anyway? Jun 4, 2020 at 12:43
  • That is called "useless use of cat". Do this instead: nc -v 192.168.1.1 5005 </dev/virtual Jun 4, 2020 at 12:44
  • I was thinking to migrate the script to a systemd unit. That's why I would like to restart entire script.
    – user340971
    Jun 4, 2020 at 12:45

1 Answer 1

0

This should work:

#!/bin/bash

if ! nc -z 192.168.1.1 5005 ; then
    sleep 1 && "$0" & exit;
fi

nc -v 192.168.56.203 5005 < /dev/virtual

Explanation:

  • nc -z will check if someone is listening on the other side
  • if no one is listening, the program will sleep for 1 sec (obviously you can change this) and then it will start another instance of itself and exit
  • if someone is listening, then the program will send /dev/virtual
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.