bashminixash

Read a null-terminated string from binary into variable using od in MINIX ash


Rather rookie question but I got stuck with it for a while: I have a problem to read and parse a string that is stored in hard drive at the address that I know ...

I don't know the length of the string, only it's maximum length say n. It has been written into n-buffer initiated with zeros so its hexdump is like xx xx xx xx 00 00 00 00 00 where xx's are hex for proper string chars.

So as I know the address of the string, I copy it into binary tmp file using using dd if=<hd> of=tmp (with proper bs/count/skip to get the n bytes of the buffer). Then in bash (or rather in MINIX ash to be precise) I try to use od to parse it and read into variable but I cannot get rid of spaces/nulls:

name=$(od -Anx -tc tmp)
echo $name

and I get J O H N \0 \0 \0 \0 \0 instead of simply JOHN


Solution

  • You can use a simple trick which relies on the fact that bash strings cannot contain a NUL character:

    name="$(cat tmp)"
    echo $name