Run shell script before shutdown – linux

before_shutdown.sh

#!/bin/bash
#remove file older than 7 days
find /var/log -name "*.log" -type f -mtime +7

#test
touch "/opt/before_shutdown_tmp_file_$(date +%s)"
  • Create systemd service
echo '[Unit]
Description=before_shutdown

[Service]
ExecStart=/bin/true
Type=oneshot
RemainAfterExit=true
ExecStop=/opt/before_shutdown.sh

[Install]
WantedBy=multi-user.target' > /etc/systemd/system/before_shutdown.service
systemctl daemon-reload

systemctl enable before_shutdown

systemctl start before_shutdown

https://unix.stackexchange.com/questions/39226/how-to-run-a-script-with-systemd-right-before-shutdown

raspberry pi fan on/off automation based on cpu temp

Note : This does not work because IO pins does not enough power to run fan.

fan.py

import RPi.GPIO as GPIO
from time import sleep
import sys

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) 

if sys.argv[1] == "on":
 GPIO.output(8, GPIO.HIGH)
 print("on")
else:
 GPIO.output(8, GPIO.LOW)
 print("off")

Dockerfile

FROM python:slim-buster
WORKDIR /fan
RUN apt update && \
    apt install python-rpi.gpio python3-rpi.gpio -y 
COPY fan.py .

Docker build

docker build -t fan .

Docker run command switch on

docker run -it --device /dev/gpiomem fan python2 fan.py on

Docker run command switch off

docker run -it --device /dev/gpiomem fan python2 fan.py off

fan.sh

#!/bin/bash

cpu=$(</sys/class/thermal/thermal_zone0/temp)

cpu_temp=$(echo "$cpu/1000" | /usr/bin/bc)
echo $cpu_temp

if(("cpu_temp" >= "65"))
then
echo "more 65 on fan"
docker run -it --device /dev/gpiomem fan python2 fan.py on
else
echo "less 65 off fan"
docker run -it --device /dev/gpiomem fan python2 fan.py off
fi

More: https://raspberrypihq.com/making-a-led-blink-using-the-raspberry-pi-and-python/

https://stackoverflow.com/questions/48441737/docker-error-no-access-to-dev-mem-try-running-as-root