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
  • 123
  • 5
  • There are plenty of (better) ways of accessing serial number https://raspberrypi.stackexchange.com/q/2086/8697 – Milliways Apr 09 '23 at 00:22

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
  • 21,900
  • 3
  • 33
  • 70
  • Not sure why they would consider a question on Raspberry PI scripting language an off-topic question. As always, I wonder why moderators would close a question that was obviously helpful, as it was closed AFTER the answer was accepted. Moderators may not find it helpful, but the users of the web site did! – codeputer Apr 09 '23 at 22:55
  • 1
    @codeputer: I'm not sure either... the logic often escapes me. They frequently declare hardware-related questions off-topic, and now software-related questions. Oddly, network-related questions seems to be surviving. So yeah... I don't understand it. – Seamus Apr 10 '23 at 00:00