Home > Blockchain >  Cmd `echo`ed to `netcat` fails while cmd `printf`ed to `netcat` passes
Cmd `echo`ed to `netcat` fails while cmd `printf`ed to `netcat` passes

Time:11-17

I am sending a command to a power supply device over TCP Ethernet using netcat (nc) on Linux. If I use echo the device fails to properly receive the command, but if I use printf it works fine. Why?

# fails
echo 'measure:voltage? ch1' | timeout 0.2 nc 192.168.0.1 9999

# works
printf 'measure:voltage? ch1' | timeout 0.2 nc 192.168.0.1 9999

References:

  1. timeout cmd: https://unix.stackexchange.com/questions/492766/usage-of-nc-with-timeouts-in-ms/492796#492796

CodePudding user response:

I suppose it fails because echo appends a carriage return.

If you want to use echo you should add -e parameter to avoid that behaviour.

CodePudding user response:

Ugh! Found it.

It looks like echo adds a trailing newline to the string, whereas printf does NOT, and this trailing newline character is interfering with the device's ability to parse the command. If I forcefully add it to the end of the printf cmd, then it fails too:

# fails:
printf 'measure:voltage? ch1\n' | timeout 0.2 nc 192.168.0.1 9999

...and it looks like you can suppress the trailing newline from echo by using -n:

# works!
echo -n 'measure:voltage? ch1' | timeout 0.2 nc 192.168.0.1 9999

# also works, of course, as stated in the question
printf 'measure:voltage? ch1' | timeout 0.2 nc 192.168.0.1 9999
  • Related