Linux配置开机自启动执行脚本都有哪些方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux配置开机自启动执行脚本都有哪些方法相关的知识,希望对你有一定的参考价值。

设置test.sh为开机要启动的脚本
[root@oldboy scripts]# vim /server/scripts/test.sh
[root@oldboy scripts]# cat /server/scripts/ test.sh
#!/bin/bash
/bin/echo $(/bin/date +%F_%T) >> /tmp/ test.log
方法一:修改/etc/rc.local
[root@oldboy ~]# ll /etc/rc.local
lrwxrwxrwx. 1 root root 13 Mar 30 10:50 /etc/rc.local -> rc.d/rc.local
修改/etc/rc.local文件
[root@oldboy scripts]# tail -n 1 /etc/rc.local
/bin/bash /server/scripts/test.sh >/dev/null 2>/dev/null
重启系统,查看结果
[root@oldboy ~]# cat /tmp/test.log
2018-03-30_12:00:10
方法二:chkconfig管理
删除掉方法一的配置
[root@oldboy ~]# vim /etc/init.d/test
#!/bin/bash
# chkconfig: 3 88 88
/bin/bash /server/scripts/test.sh >/dev/null 2>/dev/null
[root@oldboy ~]# chmod +x /etc/init.d/test
添加到chkconfig,开机自启动
[root@oldboy ~]# chkconfig --add test
[root@oldboy ~]# chkconfig --list test
test 0:off 1:off 2:off 3:on 4:off 5:off 6:off
重启系统,查看结果
[root@oldboy ~]# cat /tmp/test.log
2018-03-30_12:00:10
2018-03-30_12:33:20
操作成功
关闭开机启动
[root@oldboy ~]# chkconfig test off
[root@oldboy ~]# chkconfig --list test
test 0:off 1:off 2:off 3:off 4:off 5:off 6:off
从chkconfig管理中删除test
[root@oldboy ~]# chkconfig --list test
test 0:off 1:off 2:off 3:off 4:off 5:off 6:off
[root@oldboy ~]# chkconfig --del test
[root@oldboy ~]# chkconfig --list test
service test supports chkconfig, but is not referenced in any runlevel (run
'chkconfig --add test')
参考技术A 1.执行脚本的命令放到/etc/rc.local
2.脚本放到你想要的开机启动的级别的/ect/rc.d/rcX.d

X是开机等级
0
1
2
3
4
5
6
3.脚本放到/etc/init.d
不知道对不对
目前知道就这样么多了

linux设置开机自启动脚本的最佳方式

参考技术A

最简单粗暴的方式直接在脚本 /etc/rc.d/rc.local (和 /etc/rc.local 是同一个文件,软链)末尾添加自己的 脚本
然后,增加脚本执行权限

第二种方式是在crontab中设置

也可以设置每次登录自动执行脚本,在 /etc/profile.d/ 目录下新建sh脚本,
/etc/profile 会遍历 /etc/profile.d/*.sh

另外,几个脚本的区别:
(1) /etc/profile: 此文件为系统的每个用户设置环境信息,当用户第一次登录时,该文件被执行. 并从/etc/profile.d目录的配置文件中搜集shell的设置。

(2) /etc/bashrc: 为每一个运行bash shell的用户执行此文件.当bash shell被打开时,该文件被读取(即每次新开一个终端,都会执行bashrc)。

(3) ~/.bash_profile: 每个用户都可使用该文件输入专用于自己使用的shell信息,当用户登录时,该文件仅仅执行一次。默认情况下,设置一些环境变量,执行用户的.bashrc文件。

(4) ~/.bashrc: 该文件包含专用于你的bash shell的bash信息,当登录时以及每次打开新的shell时,该该文件被读取。

(5) ~/.bash_logout: 当每次退出系统(退出bash shell)时,执行该文件. 另外,/etc/profile中设定的变量(全局)的可以作用于任何用户,而~/.bashrc等中设定的变量(局部)只能继承 /etc/profile中的变量,他们是”父子”关系。

(6) ~/.bash_profile: 是交互式、login 方式进入 bash 运行的~/.bashrc 是交互式 non-login 方式进入 bash 运行的通常二者设置大致相同,所以通常前者会调用后者。

以上是关于Linux配置开机自启动执行脚本都有哪些方法的主要内容,如果未能解决你的问题,请参考以下文章

设置Linux开机自启动服务的常见方法都有哪些?

Linux中配置开机自启动执行脚本的方法是什么?

Linux 新增开机启动脚本

Linux 新增开机启动脚本

linux开机启动会依次加载哪些脚本?

在Linux中如何将脚本做成系统服务开机自启动?