1

Consider this short program:

#!/bin/bash

ARDUINO_SERIAL=arduino-serial/arduino-serial
PORT="/dev/cu.usbmodem1421"

VERS=$($ARDUINO_SERIAL -q -b 9600 -p $PORT -S 'V' -e '\r' -r)
echo --- VERS = $VERS
B="hello${VERS}goodbye"
echo --- B = $B

FWIW, arduino-serial is a program that sends a string to an external arduino and echoes its response to stdout.

So I would expect this little script to produce:

--- VERS = 00.01
--- B = hello00.01goodbye

but instead it's producing

--- VERS = 00.01
goodbye

I don't understand how the prefix string --- B = hello00.01 is getting "eaten" rather than echoed.

Can someone explain what's going on and how to fix this?

  • 3
    What are these for: -S 'V' -e '\r' -r? – Tomasz Jan 9 '17 at 0:49
  • 3
    +1 sounds like a carriage return line termination issue – steeldriver Jan 9 '17 at 0:53
  • After B=... put echo "$B" | hexdump -C for debugging and be amazed. – AlexP Jan 9 '17 at 0:59
  • @steeldriver (and AlexP): Sure enough, VERS actually equals "00.01\r\n". So what's the idiomatically correct way to fix this? – fearless_fool Jan 9 '17 at 1:02
  • 2
    Well, the usage section says -e --eolchar=char Specify EOL char for reads (default '\n') - presumably you should choose the default \n endings – steeldriver Jan 9 '17 at 1:15
2

Full kudos to @steeldriver for suggesting it was a carriage return line termination issue, and a tip of the hat to @AlexP for suggesting hexdump as a way to validate the theory.

The issue is that the string returned by arduino-serial had a trailing '\r\n' (aka 0x0d 0x0a), as evidenced by hexdump:

echo "$VERS" | hexdump -C
00000000  30 30 2e 30 31 0d 0a                              |00.01..|

One possible fix, and the one I chose, is to pipe the results through tr -c '\r' to strip out the return character, so the resulting script looks like this:

#!/bin/bash

ARDUINO_SERIAL=arduino-serial/arduino-serial
PORT="/dev/cu.usbmodem1421"

VERS=$($ARDUINO_SERIAL -q -b 9600 -p $PORT -S 'V' -e '\r' -r | tr -d '\r')
echo --- VERS = $VERS
B="hello${VERS}goodbye"
echo --- B = $B

which prints as expected:

--- VERS = 00.01
--- B = hello00.01goodbye

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.