Ubuntu20.04--开机自动运行脚本(命令)--方法/实例(转)

 

按语:

      ubuntu20.04  安装igh后, 使用update-rc.d, 无法自动启动ethercat,使用下文方法1,可以解决问题

本文介绍Ubuntu20.04如何开机自动运行命令。(也适用于Ubuntu22.04版本)

新版本方案(20.04版本及之后)
1.创建rc-local.service文件
sudo cp /lib/systemd/system/rc-local.service /etc/systemd/system
然后修改/etc/systemd/system/rc-local.service,在文件最下方添加如下两行:

[Install]
WantedBy=multi-user.target
Alias=rc-local.service
2.创建rc.local文件
创建/etc/rc.local,里边写自己想要运行的命令。例:

#!/bin/sh

echo "This is test" > /tmp/my.log

exit 0
给/etc/rc.local加上可执行权限

sudo chmod +x /etc/rc.local
3.测试
重启虚拟机

启动后可以发现:/tmp下已经有了my.log文件,里边内容为:"This is test"。

systemctl命令
启动服务

sudo systemctl start rc-local.service
查看服务状态

sudo systemctl status rc-local.service
老版本Ubuntu的方案
下边的方案在Ubuntu2018及之后的版本无效。

方案1:update-rc.d(2018及之前)
1.创建脚本

新建名为run_all_server.sh,内容如下:

#!/bin/bash

# 运行redis服务
cd /work/server/redis/
nohup redis-server redis.conf > redis.log 2>&1 &
2.添加执行权限

chmod +x run_all_server.sh
3.将脚本放入/etc/init.d路径下

sudo cp run_all_server.sh /etc/init.d/
4.将脚本添加到启动脚本

cd /etc/init.d/
update-rc.d run_all_server.sh defaults 90
90的含义:表明优先级,越大表示执行的越晚。

下边的命令会失败:

sudo update-rc.d /etc/init.d/run_all_server.sh defaults 90
错误信息:update-rc.d: error: unable to read /etc/init.d//etc/init.d/run_all_server.sh

5.移除脚本

update-rc.d -f run_all_server.sh remove
方案2:修改rc.local(2016及之前)
修改/etc/r.local

#!/bin/sh -e
#

# 在这里写自己的命令

exit 0

一定要将命令添加在exit 0之前。里面可以直接写命令或者执行Shell脚本文件sh。


原文链接:https://blog.csdn.net/feiying0canglang/article/details/124695749

posted on   xihong  阅读(62)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
历史上的今天:
2018-01-25 linQ to sql 查询生成的sql语句

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示