I'm trying to read serial input(/dev/tty*) character by character. I need this to parse the data following the corresponding protocol. My current method is as follows:

while read -rs -n 1 c; do
    echo Read a char:
    echo ${c}
done < "${SERIAL_PORT}"

This works, except for the fact that the data is binary and some bytes are \x00, which is not allowed as a character in a variable. My aim is to first convert the byte into a hex string(two characters) which I will then store in the variable. This is where I get stuck. What is a good way to do this? I would prefer to stay posix compliant.

  • 2
    od does this. Note that you're already not POSIX compliant since you're using other options than just -r to read.
    – Kusalananda
    Mar 7, 2019 at 8:54
  • od can convert it's input to hex, but how to get in in a variable afterwards? Mar 7, 2019 at 8:56
  • While it's definitely possible, probably you might want to read serial input via proper libraries instead of via shell script. I'd suggest pyserial via Python script. Or at a very least screen application. Those tools are designed exactly for the job. Shell scripts - not so suitable for low level stuff like that Mar 7, 2019 at 9:12
  • How fast is the serial data coming? You could do an infinite loop of c=$(dd bs=1 count=1 < ... | od ... | awk ...) but it might take so long that some data would be missed.. Mar 7, 2019 at 21:42

1 Answer 1


Using od to create hexadecimal ASCII representation for each byte/character of input, and outputting these one at a time:

od -v -An -txC <input |
awk '{ for (i = 1; i <= NF; ++i) print $i }'

This will output one hexadecimal number per line.

You may then read this with read if you wish, but it would be better if you could do your processing inside of the already existing awk code.

  • I am not sure if this is the issue, but I think od buffers until 16 bytes? Because if I remove the awk it displays as 16 bytes batches Mar 7, 2019 at 9:22
  • For this system I need the characters as soon as they're available Mar 7, 2019 at 9:23
  • 1
    @AartStuurman Then you need to use a language that can read the raw bytes from the input stream.
    – Kusalananda
    Mar 7, 2019 at 9:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .