Linux开机自动执行某些命令运行自定义脚本的方法
1) /etc/rc.d/rc.local文件
2)crontab计划任务
3)使用systemd自定义服务
4)在/etc/profile.d/下写bash文件
5)使用chkconfig管理,编辑/etc/init.d/下文件
[root@pyjydb ~]# file /etc/rc.d/rc.local
/etc/rc.d/rc.local: Bourne-Again shell script, ASCII text executable
[root@pyjydb ~]#
[root@pyjydb ~]# ls -al /etc/rc.local
lrwxrwxrwx. 1 root root 13 Sep 30 2021 /etc/rc.local -> rc.d/rc.local
比如,我们开机后要开swap,然后再做一个挂载,写一个简单的脚本

在/etc/rc.d/rc.local文件的最后添加一行即可:
bash /data/script/mount.sh
[root@pyjydb ~]# crontab -l
@reboot bash /data/script/mount.sh
注意,如果脚本里有系统命令,@reboot不一定会执行,由于系统开机初始化,很有可能系统自带命令运行环境并不满足,但crontab已经开始执行@reboot,从而造成命令运行失败。
[root@pyjydb ~]# cat /etc/systemd/system/mount.service
[Unit]
Description=auto mount
After=default.target
[Service]
ExecStart=/data/script/mount.sh
[Install]
WantedBy=default.target
然后使服务生效
[root@pyjydb ~]# systemctl daemon-reload
[root@pyjydb ~]#
[root@pyjydb ~]# systemctl enable mount
Created symlink from /etc/systemd/system/default.target.wants/mount.service to /etc/systemd/system/mount.service.
[root@pyjydb ~]#


[root@pyjydb init.d]# pwd
/etc/init.d
[root@pyjydb init.d]# cat my_mount
#!/bin/bash
# chkconfig: 2345 10 90
# description: auto mount after reboot
swapon /home/image/swap
mount -t nfs 10.105.128.127:/home/share/kefu_excel /mnt/kefu_excel/
[root@pyjydb init.d]#
[root@pyjydb init.d]# chkconfig --add my_mount
[root@pyjydb init.d]# chkconfig --list
Note: This output shows SysV services only and does not include native
systemd services. SysV configuration data might be overridden by native
systemd configuration.
If you want to list systemd services use 'systemctl list-unit-files'.
To see services enabled on particular target use
'systemctl list-dependencies [target]'.
my_mount 0:off 1:off 2:on 3:on 4:on 5:on 6:off
netconsole 0:off 1:off 2:off 3:off 4:off 5:off 6:off
network 0:off 1:off 2:on 3:on 4:on 5:on 6:off
如果要删除 chkconfig --del my_mount