参考:
https://www.linuxprobe.com/linux-cron-shell.html
https://blog.csdn.net/qq_41204464/article/details/103999467
在启动时执行 Linux 脚本
方法 #1 - 使用 cron 任务
除了常用格式(分 / 时 / 日 / 月 / 周)外,cron 调度器还支持 @reboot 指令。这个指令后面的参数是脚本(启动时要执行的那个脚本)的绝对路径。然而,这种方法需要注意两点:
- a) cron 守护进程必须处于运行状态(通常情况下都会运行),同时
- b) 脚本或 crontab 文件必须包含需要的环境变量(如果有的话,参考 StackOverflow 获取更多详细内容)。
方法 #2 - 使用 /etc/rc.d/rc.local
/etc/rc.local是/etc/rc.d/rc.local的软链接
ubuntu 16以及之前的版本
不要忘了给脚本文件添加可执行权限
chmod +x /etc/rc.d/rc.local
1) 打开rc.local脚本
sudo vi /etc/rc.local
2) 在rc.local脚本添加命令
在exit 0 前添加要执行的命令,里面可以直接写命令或者执行指定的Shell脚本文件sh
第一种:执行指定sh脚本文件
例如:让ubuntu系统实现每隔5s执行一次温度检测脚本:net-temperature.sh
第二种:开机自动执行sudo命令
#!/bin/sh -e
#
# 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.:
# 这个sudo 命令是执行sh文件,也可以是其他sudo命令可通过执行命令时将执行结果写入文件查看
sudo sh run_name.sh
exit 0
常见错误或问题:
1、方法2中的脚本没有执行,解决:尝试将脚本文件/etc/rc.local开头的 #!/bin/sh -e 改为 #!/bin/bash
2、出现过一种情况,原linux系统的 /etc/rc.local 文件中末尾没有 exit 0 代码,且
# By default this script does nothing.
语句后有一大段不知作用的代码if等,末尾添加exit 0 后在exit 0 前添加执行命令 ls > testfile.txt 脚本没有执行,去掉exit 0 后仍无法执行,将脚本文件/etc/rc.local开头的 #!/bin/sh -e 改为 #!/bin/bash 后,执行init 6 命令重启linux后,发现进入了命令行模式而非以往的图形界面模式,在命令行模式中找到 /etc/rc.local 文件打开,发现是有exit 0 的常规的开机脚本文件,添加了一些执行命令如ls后,
init 6 重启linux发现又回到了图形界面,此时图形界面中的 /etc/rc.local 与命令行模式中的一致,且脚本正常执行,脚本文件开头变回了 #! /bin/sh -e
3、在开机脚本中设置了启动指定脚本来启动docker 中的容器 FASTDFS的storage时,开机后没有正常执行,尝试在指定的脚本文件中多设置几道启动命令来解决这个问题。