0

I'm currently trying to build a shell script that sends broadcast UDP packets. My problem is that my echo is outputting the arguments instead, and I have no ideia why. Here's my script:

#!/bin/bash
# Script
var1="\xdd\x02\x00\x13\x00\x00\x00\x10\x46\x44\x30\x30\x37\x33\x45\x31\x39\x39\x45\x43\x31\x42\x39\x34\x00"
var2="\xdd\x00\x0a\x\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x02"

echo -ne $var1 | socat - UDP4-DATAGRAM:255.255.255.255:5050,broadcast
echo -ne $var2 | socat - UDP4-DATAGRAM:255.255.255.255:5050,broadcast

Using wireshark I can see the script is printing -ne as characters and also is not converting each \xHH to the correspondant ASCII character.

Thanks!

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Ricardo Alves
  • 1,071
  • 18
  • 36

2 Answers2

0

I figured my problem out. It turns out I was runninc my script with sh ./script.sh instead of bash ./script.sh

Ricardo Alves
  • 1,071
  • 18
  • 36
  • that is strange. "sh" is typically an alias to "bash" on Linux. What does "type sh" says? – toddlermenot Aug 02 '15 at 17:55
  • @toddlermenot That is "typically" true on some distros, but not on others. Even then, Bash behaves differently when invoked as `sh`. You really should never expect `sh` to run Bash, even if that might be how it's implemented at this point in time on your particular configuration. See also [Difference between `sh` and `bash`](https://stackoverflow.com/questions/5725296/difference-between-sh-and-bash) – tripleee Nov 04 '22 at 07:23
0

echo implementations are hopelessly inconsistent about whether they take command options (like -ne) or simply treat them as part of the string to print, and/or whether they interpret escape sequences in the strings to print. It sounds like you're seeing a difference between bash's builtin version of echo vs. (I'm guessing) the version in /bin/echo. I've also seen it vary even between different versions of bash.

If you want consistent behavior for anything nontrivial, use printf instead of echo. It's slightly more complicated to use it correctly, but IMO worth it because your scripts won't randomly break because echo changed for whatever reason. The tricky thing about printf is that the first argument is special -- it's a format string in which all escape sequences are interpreted, and any % sequences tell it how to add in the rest of the arguments. Also, it doesn't add a linefeed at the end unless you specifically tell it to. In this case, you can just give it the hex codes in the format string:

printf "$var1" | socat - UDP4-DATAGRAM:255.255.255.255:5050,broadcast
printf "$var2" | socat - UDP4-DATAGRAM:255.255.255.255:5050,broadcast
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151