Raspberry Pi Model As Environment Variable

From Wiki
Jump to navigationJump to search

Overview

Run a script at start that leaves an environment variable set.

In this particular case, an application needed to know which version of a Raspberry Pi it was running on. This information is available in the kernel ring buffer, and is available in the /var/log/messages. I did not want to grep the log every time I needed the information, rather, I wanted an environment variable set.

Copy the text below into the respective files (you'll need to be root), then execute the following commands.

sudo chmod 755 /etc/init.d/rpimodel.sh
sudo chmod 644 /etc/profile.d/rpimodel.sh
sudo systemctl enable rpimodel

Next time the system is started, /etc/rpimodel should contain the Raspberry Pi model, and the environment variable RPIMODEL should be set.

$ cat /etc/rpimodel
RPIMODEL="Raspberry Pi Zero W Rev 1.1"
$ set | grep RPIMODEL
RPIMODEL='Raspberry Pi Zero W Rev 1.1'
$

/etc/init.d/rpimodel.sh

#! /bin/sh
### BEGIN INIT INFO
# Provides:          rpimodel
# Required-Start:    $syslog $network +ntp
# Required-Stop:     $null
# Should-Start:      glibc
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Set RPIMODEL based on dmesg
# Description:       Read the 'Machine model:' string using 'dmesg'
#                    and export it as RPIMODEL variable.
### END INIT INFO

PATH=/sbin:/bin

. /lib/init/vars.sh
. /lib/lsb/init-functions

do_start () {
  RPIMODEL=`dmesg | grep -oP 'fdt:Machine model: \K.*'`
  export RPIMODEL
  echo "RPIMODEL=\"${RPIMODEL}\"" >/etc/rpimodel
  exit 0
}

case "$1" in
  start|"")
        do_start
        ;;
  restart|reload|force-reload)
        echo "Error: argument '$1' not supported" >&2
        exit 3
        ;;
  stop)
        # No-op
        ;;
  status)
        # No-op
        ;;
  *)
        echo "Usage: rpimodel.sh [start|stop]" >&2
        exit 3
        ;;
esac

:

/etc/profile.c/rpimodel.sh

if [ -r /etc/rpimodel ]; then
    . /etc/rpimodel
    export RPIMODEL
fi

/lib/systemd/system/rpimodel.service

[Unit]
SourcePath=/etc/init.d/rpimodel.sh
Description=Set RPIMODEL based on dmesg
Before=runlevel2.target runlevel3.target runlevel4.target runlevel5.target
After=glibc.service

[Service]
Type=forking
Restart=no
TimeoutSec=5min
IgnoreSIGPIPE=no
KillMode=process
GuessMainPID=no
RemainAfterExit=yes
SysVStartPriority=3
ExecStart=/etc/init.d/rpimodel.sh start
ExecStop=/etc/init.d/rpimodel.sh stop

[Install]
WantedBy=multi-user.target