0

I'm working with a paired down embedded Linux installation that does not support bash, only sh across a ssh terminal. I need to send hex data to a connected USB device /dev/ttyUSB0. I'm able to do this easily enough with bash (on a desktop installation of Ubuntu 18.04) using echo -en '\x01\x02\x03' > /dev/ttyUSB0, but it seems that the backslash escapes are not supported by sh. Is there another relatively easy (or even not-so-easy) way to do this with sh?

Unfortunately, $SHELL --version is not returning anything. Kernel version is 4.1.0.

Jim Fell
  • 265

3 Answers3

1

This is one of the reasons why printf is better than echo. Implementations of echo vary in if and how they support options and backslash-escapes, but all versions of printf should support backslash-escapes.

The only catch is that only octal escapes, like \001 are standard, so \x01 might not be available everywhere even with printf. You could start by trying printf "\x01" though.

If that doesn't work, you'll have to switch to octal. Either do the conversion off-line with any programmer's calculator, or use something like printf "%o\n" "0x61" to convert or use something like this to batch-convert your string:

echo 'foo\x01\x61' | perl -pe 's/\\x([0-9a-fA-F]{2})/sprintf("\\%03o", hex($1))/ge'

(it should give foo\001\141)

ilkkachu
  • 138,973
0

You are mixing slash / and backslash \.

Escaping is done with backslash:

echo -en '\x01\x02\x03' > /dev/ttyUSB0
White Owl
  • 5,129
0

In the end, I used my Ubuntu desktop to create binary files.

echo -en '\x01\x02\x03' > binary.file

Then, after copying the binary file to my system running ash shell, I cat that file in my script to the USB.

cat binary.file > /dev/ttyUSB0

It'd be nice if there were a better way to do this, without the intermediary step of creating a set of binary files, but this'll work for now.

Jim Fell
  • 265