编写脚本是为了开机自动启动各种服务
- 进入终端输入:
创建一个后缀为.sh的脚本文件
touch test.sh
- 编辑脚本
vim test.sh
- 编写test.sh脚本,例如:
#!/bin/bash
### begin init info
# provides: test
# required-start: $remote_fs $syslog
# required-stop: $remote_fs $syslog
# default-start: 2 3 4 5
# default-stop: 0 1 6
# short-description: start test
# description: start test
### end init info
#此处编写脚本内容
cd /home/desktop/
./test.sh
exit 0
以#!/bin/bash
开头 中间写脚本内容 exit 0
结尾
-
移动test.sh文件到/etc/init.d目录下
sudo mv test.sh /etc/init.d/
给文件增加权限
chmod +750 test.sh
-
设置开机自动启动
sudo update-rc.d test.sh defaults
-
完成
说明,Ubuntu18.04这种方法无效!
Ubuntu18.04设置程序开机自启
编辑rc.local.service并添加[Install]内容:(注意:1.文件位置,2.是Install添加了两行内容)
sudo vi /lib/systemd/system/rc.local.service
[Install]
WantedBy=multi-user.target
Alias=rc-local.service
如果你之前是在/etc/systemd/system/rc-local.service
下,请先rm掉
sudo rm /etc/systemd/system/rc-local.service
启用服务
sudo systemctl enable rc.local.service
sudo systemctl status rc-local.service
该文件是自动执行的脚本文件,把要执行的内容放在exit 0
前就可以
#!/bin/bash
#
# 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
exit 0
重启电脑,检查你的脚本是否执行了
reboot
cat /usr/local/test.txt