方法一:rc-local方法
1、建立rc-local.service文件
sudo vi /etc/systemd/system/rc-local.service
2、将下列内容复制进rc-local.service文件
[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99
[Install]
WantedBy=multi-user.target
3、创建文件rc.local
sudo vi /etc/rc.local
4、将下列内容复制进rc.local文件
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
#echo "看到这行字,说明添加自启动脚本成功。" > /usr/local/test.log
/bin/bash /home/xqkang/test/print.sh >> /usr/local/print.log 2>&1
exit 0
脚本:
#sleep 60
echo "$(date): Starting "
start=$SECONDS
for (( i=0; i<30; i++));do
echo "I am $i !!!"
sleep 2
done
echo "$(date): Finished "
finish=$SECONDS
echo "elapsed = $(($finish-$start)) seconds"
5、给rc.local加上权限
sudo chmod +x /etc/rc.local
6、启用服务
sudo systemctl enable rc-local
7、启动服务并检查状态
sudo systemctl start rc-local.service
sudo systemctl status rc-local.service
8、重启并检查test.log文件
cat /usr/local/test.log
如果能看到内容,说明设置成功,你就可以通过编辑rc.local文件来设置启动脚本了
问题:重启之后必须要执行完开机启动的脚本之后才能进入到Ubuntu登陆的界面
方法二:crontab 设置开机启动
xqkang@xqkang:~$ crontab -e
#*/1 * * * * /home/xqkang/test.sh
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
@reboot ( sleep 120 ; /bin/bash /home/xqkang/test/print.sh >> /usr/local/print.log 2>&1)
@reboot:设置开机启动
sleep 120 ;睡眠120秒
/bin/bash /home/xqkang/test/print.sh >> /usr/local/print.log 2>&1 执行的脚本并把日志写到/usr/local/print.log文件中
这种开机启动的任务不会出现上一个方法中出现的问题
方法三:/etc/profile.d/
将写好的脚本(.sh文件)放到目录 /etc/profile.d/ 下,系统启动后就会自动执行该目录下的所有shell脚本。
方法四:通过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 脚本文件名 操作后就已经添加了