systemd开关机脚本执行方法
[Unit]
Description=MCU开关机任务
DefaultDependencies=no
Before=reboot.target poweroff.target halt.target shutdown.target
After=timers.target
[Service]
Type=oneshot
ExecStart=/opt/arash/bin/check.sh
User=root
TimeoutSec=6
[Install]
WantedBy=reboot.target poweroff.target timers.target
脚本
date +"%D %T"
mcu='/opt/arash/bin/MCU'
LOG_FILE="/var/log/mcu.log"
if systemctl list-jobs | grep -q 'reboot.target.*start'; then
echo "$(date): Reboot detected. Performing reboot-specific tasks..." >> $LOG_FILE
$mcu reboot
elif systemctl list-jobs | grep -q -E 'poweroff.target.*start|halt.target.*start'; then
echo "$(date): Shutdown/Power-off detected. Performing shutdown-specific tasks..." >> $LOG_FILE
$mcu shutdown
elif systemctl list-jobs | grep -q 'setvtrgb.service.*start';then
echo "$(date): system init detected. Preforming RTC tasks..." >> $LOG_FILE
$mcu timesync
timedatectl show
else
echo "$(date): Neither reboot nor poweroff detected in job list. Fallback action." >> $LOG_FILE
systemctl list-jobs >> $LOG_FILE
fi
sync