系统启动后自动执行脚本

编写脚本代码
[root@localhost ~]# vim /shell/demo.sh
#!/usr/bin/env bash
touch /tmp/demo.`date +"%Y%m%d%H%M%S"`.log
[root@localhost ~]# chmod +x /shell/demo.sh # 脚本需要有执行权限
 
 
 
把脚本路径追加到/etc/rc.d/rc.local文件
[root@localhost ~]# cp /etc/rc.d/rc.local /etc/rc.d/rc.local.default
[root@localhost ~]# cp /etc/rc.d/rc.local /etc/rc.d/rc.local.bak
[root@localhost ~]# chmod +x /etc/rc.d/rc.local
[root@localhost ~]# vim /etc/rc.d/rc.local
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.
 
touch /var/lock/subsys/local
 
# 系统启动后需要自动执行的脚本代码或脚本文件硬盘路径
/shell/demo.sh
[root@localhost ~]# shutdown -r now # 重启系统验证是否会自动执行脚本

需要注意的是/etc/rc.d/rc.local是在系统启动过程中执行的,如果要执行的脚本依赖某些服务,那么脚本就有可能执行失败,例如脚本依赖MySQL服务,但是执行脚本时MySQL还没启动,就会执行失败。
 
由于/etc/rc.d/rc.local里的脚本不能控制执行时机,所以Linux没有给该文件执行权限,并且Linux也不建议使用该文件实现开机执行脚本,而是推荐使用systemd来实现。

Copyright © 2023 码农人生. All Rights Reserved