ubuntu 开机自启脚本技巧
介绍 Ubuntu 中实现开机启动脚本的三种方法:
/etc/init.d 方法
gnome-terminal 方法
rc.local 方法
测试脚本 test.sh
#!/bin/bash
# test.sh
cd /home/Desktop/
ls
echo "OK!"
exit 0
1. /etc/init.d 方法
sudo mv test.sh /etc/init.d/
sudo chmod 777 test.sh
sudo update-rc.d test.sh defaults
如果需要设置启动优先级: 100表示优先级,数越大,执行的越晚
sudo update-rc.d test.sh defaults 100
如果要移除脚本:
cd /etc/init.d
sudo update-rc.d -f test.sh remove
2. gnome-terminal 方法
2.1 间接启动
新建终端时,终端会自动执行~/.bashrc,应用该方法可实现开机自启动
# 将命令写入~/.bashrc
source ~/.bashrc
启动 ubuntu 的 启动应用程序首选项
gnome-session-properties
命令处写入gnome-terminal,→添加,重启即可生效。
2.2 直接启动
在上述命令处写入:
gnome-terminal -x bash -c "/home/User/Desktop/test.sh"
重启即可生效。
3. rc.local 方法
rc.local脚本会在ubuntu开机后自动执行,因此我们可以将启动命令写在此文件中。
在 Ubuntu 中,rc.local 服务默认被隐藏,可以通过手动配置实现开机自启动脚本功能。
确认 rc.local 服务状态
sudo systemctl status rc-local.service
如显示如下,则表示该服务未配置
rc-local.service - /etc/rc.local Compatibility
Loaded: loaded (/usr/lib/systemd/system/rc-local.service; static)
Drop-In: /usr/lib/systemd/system/rc-local.service.d
└─debian.conf
Active: inactive (dead)
Docs: man:systemd-rc-local-generator(8)
可以如下配置启动 rc.local 服务
复制服务文件
sudo cp /usr/lib/systemd/system/rc-local.service /etc/systemd/system/
配置服务文件
sudo vi /etc/systemd/system/rc-local.service
确保内容如下:
[Unit]
Description=/etc/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/bin/bash /etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no
[Install]
WantedBy=multi-user.target
重新加载服务配置
sudo systemctl daemon-reload
创建 rc-local 文件并赋予执行权限
sudo touch /etc/rc.local
sudo chmod +x /etc/rc.local
编辑 rc.local 脚本添加需开机执行的命令
#!/bin/bash
# rc.local
cd /home/User/Desktop/ && ./test.sh
exit 0
启动并启用服务
sudo systemctl enable rc-local.service
sudo systemctl start rc-local.service
通过以上步骤,可以在 Ubuntu 中成功启用并使用 rc.local 实现开机自启动功能。
评论
其他文章