linux 添加开机启动项的三种方法。
编辑文件 /etc/rc.local
/etc/rc.d/rc.local
(和/etc/rc.local
是同一个文件
输入命令:vim /etc/rc.local 将出现类似如下的文本片段:
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
/etc/init.d/mysqld start #mysql开机启动
/etc/init.d/nginx start #nginx开机启动
/etc/init.d/php-fpm start #php-fpm开机启动
/etc/init.d/memcached start #memcache开机启动
#在文件末尾(exit 0之前)加上你开机需要启动的程序或执行的命令即可(执行的程序需要写绝对路径,添加到系统环境变量的除外),如:
/usr/local/thttpd/sbin/thttpd -C /usr/local/thttpd/etc/thttpd.conf
二、在/etc/init.d目录下添加自启动脚本
linux在“/etc/rc.d/init.d”下有很多的文件,每个文件都是可以看到内容的,其实都是一些shell脚本或者可执行二进制文件
Linux开机的时候,会加载运行/etc/init.d目录下的程序,因此我们可以把想要自动运行的脚本放到这个目录下即可。系统服务的启动就是通过这种方式实现的。
每次登录自动执行
自己写一个shell脚本
将写好的脚本(.sh文件)放到目录 /etc/profile.d/ 下,系统启动后就会自动执行该目录下的所有shell脚本。
也可以设置每次登录自动执行脚本,在/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 运行的通常二者设置大致相同,所以通常前者会调用后者。
---------------------
通过chkconfig命令设置
将启动文件cp到 /etc/init.d/或者/etc/rc.d/init.d/(前者是后者的软连接)下
vim 启动文件,文件前面务必添加如下三行代码,否侧会提示chkconfig不支持
#!/bin/sh 告诉系统使用的shell,所以的shell脚本都是这样
#chkconfig: 35 20 80 分别代表运行级别,启动优先权,关闭优先权,此行代码必须
#description: http server(自己随便发挥)//两行都注释掉!!!,此行代码必须
chkconfig --add 脚本文件名 操作后就已经添加了
四、把脚本注册为系统服务
在/etc/init.d下新建示例脚本文件(startTest.sh),该脚本会启动/opt/test.sh。内容如下:
. /etc/init.d/functions
start() {
echo "Starting my process "
cd /opt
./test.sh
}
stop() {
killall test.sh
echo "Stoped"
}
写了脚本文件之后事情还没有完,继续完成以下几个步骤:
chmod +x startTest #增加执行权限
chkconfig --add startTest #把startTest添加到系统服务列表
chkconfig startTest on #设定startTest的开关(on/off)
chkconfig --list startTest.sh #就可以看到已经注册了startTest的服务
在crontab中设置(没试过)