Linux开机自启脚本与配置

# 场景

写了个有趣的脚本start.sh,需求是开机后自启,最好还可以定义多久自启。

环境:Linux Ubuntu20.04

脚本目录:/home/bear/start.sh

 

# Method 1 - 使用 Crontab

最为简单的方式:创建一个 cron 任务,这个任务在系统启动后等待 5秒,然后执行命令和脚本。

$ crontab -e

选择一个编辑器后然后输入下行内容:

@reboot ( sleep 5; sh /home/bear/start.sh )

 

# Method 2 - 使用 rc.local

这种方法会利用 /etc/ 中的 rc.local 文件来在启动时执行脚本与命令。

不过我们首先需要为 /etc/rc.local 添加执行权限:

$ sudo chmod +x /etc/rc.local

然后将要执行的脚本加入其中:

$ sudo vim /etc/rc.local

在文件最后加上:

sh /home/bear/start.sh &

 注意:- 启动时执行的脚本,请一定保证是以 exit 0 结尾的。

 

# Method 3 - 使用 .bashrc

无desktop的环境时,如tty shell用这个就很舒服

# Auto Run
if [ $(ps -ef|grep xorg|grep -v grep|wc -l) -eq 0 ]; then
    while true; do
        ./start.sh
        if [ something ]; then
            break
        fi
    done
fi

 

补充:

只用tty来玩的环境下,用systemd配置用户开机自动登入系统,以下为tty1配置:

autologin edit:
sudo systemctl edit getty@tty1

copy and reboot:
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin [User] --noclear %I screen-256color

restart:
sudo systemctl daemon-reload
sudo systemctl start getty@tty1.service

 

 

补充参考资料:
https://zdyxry.github.io/2020/03/06/systemd-%E5%B8%B8%E7%94%A8%E6%93%8D%E4%BD%9C%E5%8F%8A%E9%85%8D%E7%BD%AE/
http://www.panwenbin.com/52

 

posted @ 2020-07-27 19:49  kumata  阅读(535)  评论(0编辑  收藏  举报