How to make custom script that runs automatically during boot up in RHEL7
https://access.redhat.com/solutions/1163283
SOLUTION 已验证 - 已更新 2019年三月14日06:49 -
环境
- Red Hat Enterprise Linux 7
问题
- How to make custom script that runs automatically during boot up in RHEL7?
- In RHEL 5 and 6, we were using automatic startup feature of RHEL through /etc/rc.d/init.d.
决议
NOTE: Red Hat does not support implementation of custom scripts, including custom systemd startup scripts. This article is provided as a how-to and Red Hat will not troubleshoot any issues after the implementation of the steps provided here. For more information please see the Production Support Scope of Coverage
- Related solutions:
+ How to configure a command, script, or daemon to run after boot has finished in RHEL 7
+ How to allow a custom service script in RHEL7 to run in the foreground and accept user input
+ How to configure a systemd service in RHEL7 to run as a custom user or group
-
Create a new service unit file at
/etc/systemd/system/example.service
1 with content based on the following[Unit] Description=Example Service Script description goes here After=network.target [Service] Type=simple ExecStart=/usr/local/sbin/example.sh TimeoutStartSec=0 [Install] WantedBy=default.target
Optionally, consult footnotes for explanation:
After=
2Type=
3TimeoutStartSec=
4 -
Create the example shell script mentioned in the unit file's
ExecStart
directive, e.g., save the following to/usr/local/sbin/example.sh
, making sure the file is executable#!/bin/bash z=0 for i in {1..5}; do sleep 1m ((z++)) wall example.sh: finished minute ${z} done wall example.sh: COMPLETELY FINISHED
-
Reload the
systemd
process to consider newly createdexample.service
OR every time whenexample.service
gets modified.# systemctl daemon-reload
-
Enable the service and then reboot to test
# systemctl enable example.service # reboot
-
The unit file should be located in either
/usr/lib/systemd/system/
or/etc/systemd/system/
. See UNIT LOAD PATH section inman systemd.unit
. ↩ -
After=
If the script needs any other system facilities (networking, etc), modify the[Unit]
section to include appropriateAfter=
,Wants=
, orRequires=
directives, as described in:man systemd.unit
. ↩ -
Type=
SwitchType=simple
forType=idle
in the[Service]
section to delay execution of the script until all other jobs are dispatched (seeman systemd.service
for even more choices -- e.g.,Type=oneshot
can be useful in concert with other services). ↩ -
TimeoutStartSec=
When a service doesn't signal start-up completion withinTimeoutStartSec
, systemd considers the service failed; for long-running shell scripts it is essential to modifyTimeoutStartSec
or disable the timeout logic altogether as above, withTimeoutStartSec=0
. Seeman systemd.service
for more details. ↩