创建。sh文件

  1. #! /bin/bash
  2. touch /home/pi/test.txt

赋予权限 chmod 777 test.sh
修改 /etc/rc.local 文件

  1. #!/bin/sh -e
  2. #
  3. # rc.local
  4. #
  5. # This script is executed at the end of each multiuser runlevel.
  6. # Make sure that the script will "exit 0" on success or any other
  7. # value on error.
  8. #
  9. # In order to enable or disable this script just change the execution
  10. # bits.
  11. #
  12. # By default this script does nothing.
  13. # Print the IP address
  14. _IP=$(hostname -I) || true
  15. if [ "$_IP" ]; then
  16. printf "My IP address is %s\n" "$_IP"
  17. fi
  18. #自己写的脚本所在的绝对目录
  19. /home/pi/test.sh
  20. exit 0

rc.local是否执行失败

  • 终端输入该命令查看rc.local执行失败的原因
    1. systemctl status rc.local

    重启rclocal命令

    | systemctl restart rc-local | | —- |

可以通过这样来检测开机启动是否能成功,而不是每次都要重启,重启!
6 注意事项

6.1 权限

要加上对应的执行权限

6.2 绝对路径

尽量使用绝对路径,~对应的/home/ubuntu有时会被代替为/root,从而出错

6.3 bash 代替 sh

#!/bin/sh
对应bin中的dash,版本老,有些新命令不支持,从而报错
#!/bin/bash 推荐

6.4 rc.local中命令加权限

如下语句,如果脚本中需要sudo权限的操作会执行失败

sh /run/media/mmcblk0p4/Sen/test_start.sh &

正确如下,注意设置管理用户使用sudo命令免密模式

sudo sh /run/media/mmcblk0p4/Sen/test_start.sh &

你的命令需要长时间运行(例如死循环)或者运行后不能退出,那么你必须确保在命令的最后添加“&”符号让命令运行在其它进程,例如: