I use this in a script

echo $(echo "sign 00:07:32:46:04:75" | socat UDP4-DATAGRAM: -)

but this does immediately stop and I get no answer from the server

if I do

echo $(echo "sign 00:07:32:46:04:75" | socat -t5 UDP4-DATAGRAM: -)

it always waits the 5 seconds also when the repsonse would be available after 1 second.

Is there a way to stop the command immediatley after I received the first message?


Assuming the answer is one newline-delimited line of text, with bash, you could always do:

IFS= read -r answer < <(
  echo 'sign 00:07:32:46:04:75' |
    socat -t 5 - UDP4-DATAGRAM:

That would return as soon as there's an answer and socat would be left running in background for the remaining time.

In zsh, you'd need to add a & at the end of the echo|socat pipeline for it not to wait for it. You may actually want to add it for bash as well to be future-proof in case bash decides to change the behaviour in the future.

If the answer can be more than one line or is not newline delimited, with zsh you could do:

zmodload zsh/system
(echo 'sign 00:07:32:46:04:75' |
  socat -t 5 - UDP4-DATAGRAM: &) | sysread answer

The sysread builtin does one read() system call of size 8192. That assumes socat writes the answer on the pipe in one write() system call (which it does).

Portably, you could always resort to dd for that:

  (echo 'sign 00:07:32:46:04:75' |
    socat -t 5 - UDP4-DATAGRAM: &) |
    dd bs=8192 count=1 2> /dev/null

(note that command substitution strips all trailing newline characters).

If you wanted to avoid socat hanging around for those few extra seconds after that, you could do something like:

  (echo 'sign 00:07:32:46:04:75' |
    sh -c 'echo "$$"
           exec socat -t 5 - UDP4-DATAGRAM: &
  ) | {
    IFS= read pid
    dd bs=8192 count=1 2> /dev/null
    kill -s PIPE "$pid"
  • thx for the great answer! – user2071938 Nov 22 '17 at 12:59

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.