ubuntu中编写shell脚本开机自动启动

编写脚本是为了开机自动启动各种服务

  1. 进入终端输入:
    创建一个后缀为.sh的脚本文件
    touch test.sh
  2. 编辑脚本
    vim test.sh
  3. 编写test.sh脚本,例如:
#!/bin/bash
 
### begin init info
# provides:     test
# required-start:  $remote_fs $syslog
# required-stop:   $remote_fs $syslog
# default-start:   2 3 4 5
# default-stop:   0 1 6
# short-description: start test
# description:    start test
### end init info
 
#此处编写脚本内容
cd /home/desktop/
./test.sh
exit 0

#!/bin/bash开头 中间写脚本内容 exit 0结尾

  1. 移动test.sh文件到/etc/init.d目录下

    sudo mv test.sh /etc/init.d/

    给文件增加权限

    chmod +750 test.sh

  2. 设置开机自动启动
    sudo update-rc.d test.sh defaults

  3. 完成

说明,Ubuntu18.04这种方法无效!

Ubuntu18.04设置程序开机自启
编辑rc.local.service并添加[Install]内容:(注意:1.文件位置,2.是Install添加了两行内容)

sudo vi /lib/systemd/system/rc.local.service

[Install]
WantedBy=multi-user.target
Alias=rc-local.service

如果你之前是在/etc/systemd/system/rc-local.service下,请先rm掉

sudo rm /etc/systemd/system/rc-local.service

启用服务

sudo systemctl enable rc.local.service
sudo systemctl status rc-local.service

该文件是自动执行的脚本文件,把要执行的内容放在exit 0前就可以

#!/bin/bash
#
# 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.
echo "看到这行字,说明添加自启动脚本成功。" > /usr/local/test.log
exit 0

重启电脑,检查你的脚本是否执行了

reboot
cat /usr/local/test.txt
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值