🌐 이 글의 한국어 원문이 있습니다.한국어 원문 보기 →

· 4 min read

When Do Linux Init Scripts Run?

On Linux, there are several ways to run a script automatically 'at boot.'

1. Crontab reboot (@reboot)

You can have crontab run a script 'at boot.'

Open the crontab page with crontab -e.

crontab @reboot /usr/bin/logger '[init] crontab'

If you add it under your own account, it runs with your account's permissions; if you add it under the root account, it runs as root.

2. rc.local file script

The rc.local file is a script that runs at boot.

Open the file with vi /etc/rc.loacl.

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# Print the IP address


/usr/bin/logger '[init] rc.local'

exit 0

Just add your command and it runs automatically. The file says you must return 0 on exit. If an error occurs, a log entry is written to syslog under the name rc.local.

3. init.d service

For something a bit heavier than rc.local, you can write a 'service script' and run it as a daemon. In this case, besides running automatically at boot, you can also stop, restart, and otherwise control the service with the service command. This makes it a daemon service in the full sense.

A detailed explanation of writing init.d service scripts is at https://jcdgods.tistory.com/360. Here I'll just write a simple test script.

#!/bin/sh
### BEGIN INIT INFO
# Provides:          test_service
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Sample service init.d script
# Description:       Sample service init.d script
### END INIT INFO

/usr/bin/logger '[init] init.d'

exit 0

So when, and in what order, does each of these run? If you add the above, reboot, and then check the logs, you get the following result.

pi@raspberrypi:~ $ tail -1000 /var/log/syslog | grep "\[init\]"
May 12 21:10:54 raspberrypi root: [init] init.d
May 12 21:10:54 raspberrypi CRON[421]: (pi) CMD (/usr/bin/logger '[init] crontab')
May 12 21:10:54 raspberrypi pi: [init] crontab
May 12 21:10:55 raspberrypi root: [init] rc.local

The second log line says the script is about to be run, and the line that follows is the result of running the script.

You can see the execution order is daemon service (init.d) → crontab (crontab) → rc.local.

Use this order as a reference so you can run things in the order you need.

Addendum: these days, using the rc.local file is discouraged. See the link below for details.

https://raspberrypi.stackexchange.com/questions/114125/rc-local-shell-script-to-run-socket-programraspberrypi.stackexchange.com

Related posts

Home