1

Newbie question, but I'm missing something

I'm issuing this command on my raspberry pi (zero 2W) cat /sys/firmware/devicetree/base/serial-number

which works nicely. Cat will output the command to stdout... but I want the output to a memory variable..

mcuSerialNumber=$( cat /sys/firmware/devicetree/base/serial-number )

Should, from what i read, put the output of cat to the memory variable.. but I get enter image description here

if I (interactively) use this command cat /sys/firmware/devicetree/base/serial-number enter image description here

All i'm trying to do is read that file, and put the contents (red box) into a memory variable... argh .. newbie I know

codeputer
  • 143
  • 6

1 Answers1

1

It's just a misunderstanding of the data type really, and you actually have the answer you probably wanted if you're willing to ignore the warning.

You can see this by sending your result to stdout using echo (remember, cat gave a warning - not an error):

$ mcuSerialNumber=$(cat /sys/firmware/devicetree/base/serial-number)
-bash: warning: command substitution: ignored null byte in input
$ echo $mcuSerialNumber
00000000eccd2fff

Let me attempt an explanation: The data at /sys/firmware/devicetree/base/serial-number is a null-terminated string - which cat is not designed to handle - at least not without a squawk.

You have two choices: ignore the squawk/warning, or read it using a different method; e.g.:

  • using the little-known strings utility:
$ strings /sys/firmware/devicetree/base/serial-number
00000000eccd2fff
  • or tr:
$tr < /sys/firmware/devicetree/base/serial-number -d '\0'
00000000eccd2fff
  • or sed
$ sed 's/\0//' /sys/firmware/devicetree/base/serial-number
0000000eccd2fff
  • or awk
$ awk -F /0 'NR == 1 { print $0 }' /sys/firmware/devicetree/base/serial-number
00000000eccd2fff

Alternatively, the same serial number is also available in the file /proc/cpuinfo file, but not a null-terminated string, so you can do something like this:

$ grep Serial /proc/cpuinfo
Serial      : 00000000eccd2fff
Seamus
  • 23,558
  • 5
  • 42
  • 83