使用 systemd 服务
本方法仅适用于 systemd 系统。如何区分是不是 systemd 系统?很简单,只需运行
ps aux
命令,查看 pid 为 1 的进程是不是 systemd 。
为了实现目的,我们需要创建一个 systemd 启动服务,并把它放置在 /etc/systemd/system/ 目录下。
我们创建的 systemd 启动服务如下。请注意,这时后缀是 .service ,而不是 .sh 。
vim auto_run_script.service
[Unit]
Description=Run a Custom Script at Startup
After=default.target
[Service]
ExecStart=/home/startars.sh
[Install]
WantedBy=default.target
从服务的内容可以看出来,我们最终还是会调用 /home/alvin/auto_run_script.sh 这个脚本。
然后,我们再把这个脚本放置在 /etc/systemd/systerm/ 目录下,之后我们再运行下面两条命令来更新 systemd 配置文件,并启动服务。
$ systemctl daemon-reload
$ systemctl enable auto_run_script.service
万事俱备之后,我们就可以重启系统啦。
reboot
ps:有些时候需要在sh目录下启动sh才有效,这时候的解决办法是重新创建一个脚本类似
vi /home/startars.sh
内容
/home/alvin/
bash auto_run_script.sh
然后把/etc/systemd/system/目录下的auto_run_script.service的内容改为
[Unit]
Description=Run a Custom Script at Startup
After=default.target
[Service]
ExecStart=/home/startars.sh
[Install]
WantedBy=default.target