tags: systemd

Make your own script with systemd

Recent linux system uses systemd instead of SysV init. So you cannot use /etc/rc.local for your housekeeping script with systemd, I’ve tried to migrate my own script with systemd environment. Here is my example which works one time per system startup.

1. make your own script(example: /root/synchome.sh

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/bin/sh
#
# my home directory
#
DAT=`date`
echo "script start $DAT" > /root/log
BKF=`find /mnt/nfs/flyback/flyback -mindepth 1 -maxdepth 1|grep -v lock|sort|tail -1`
# wait until autofs mount is ready
while [ "$BKF" = "" ]; do
   BKF=`find /mnt/nfs/flyback/flyback -mindepth 1 -maxdepth 1|grep -v lock|sort|tail -1`
done
if [ -d $BKF ] ; then
   DIRPRFX="/home/mkiuchi/"
   BKF=$BKF$DIRPRFX
   echo "source directory $BKF" >> /root/log
   rsync -auvz --delete --ignore-errors $BKF $DIRPRFX >> /root/log 2>&1
   # clean chromium lock file
   if [ -L "/home/mkiuchi/.config/chromium/SingletonLock" ]; then
     echo "found chromium lockfile" >> /root/log
     rm -f /home/mkiuchi/.config/chromium/SingletonLock
   fi
else
   echo "backupfile not found. aborted." >> /root/log
   exit
fi

DAT=`date`
echo "script end $DAT" >> /root/log

2. make configuration file for systemd(example: /root/synchome.service)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
[Unit]
Description=Home Directory Synchronization
Require=autofs.service
After=autofs.service

[Service]
Type=oneshot
ExecStart=/root/synchome.sh
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

3. chmod 755 /root/synchome.sh

4. cd /etc/systemd/system ; ln -s /root/synchome.service .

5. systemctl daemon-reload

I cannot determine how to identify the work of systemd, so my own script writes own log.