1. 程式人生 > >Ubuntu:開機自啟動指令碼

Ubuntu:開機自啟動指令碼

1.獨立指令碼

1).編寫要執行指令碼的sh檔案mysetup.sh

#!/bin/sh
### BEGIN INIT INFO
# Provides:          land.sh
# Required-start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the svnd.sh daemon
# Description:       starts svnd.sh using start-stop-daemon
### END INIT INFO

#任務指令碼
#進入要執行指令碼目錄
cd /home/cbuav/working/opencv/target_land
#取得root許可權,'123456'為密碼,不用加引號,'ls'無實際作用
echo 123456|sudo -S ls
#執行指令碼./bin/mywork,sudo -S需要加上
sudo -S ./bin/mywork
#任務指令碼
  • 註釋部分是必須內容,ubuntu 16.04中一定要加上該LSB資訊,不然放入啟動指令碼的時候會報錯無法開機啟動。
  • 任務指令碼中,一般需要用到root許可權,取得root許可權和實際任務語句最好分開寫,有些情況下寫在一起不會成功。

2).將該sh檔案移動到/etc/init.d/目錄下,並修改許可權

cp mysetup.sh /etc/init.d
sudo chmod 755 /etc/init.d/mysetup.sh
 cd /etc/init.d
 sudo update-rc.d mysetup.sh defaults 95
  • 其中數字95是指令碼啟動的順序號,按照自己的需要相應修改即可。在你有多個啟動指令碼,而它們之間又有先後啟動的依賴關係時你就知道這個數字的具體作用了。

4).解除安裝啟動指令碼

 cd /etc/init.d
sudo update-rc.d -f mysetup.sh remove

2.在rc.local檔案中新增啟動指令碼

rc.local指令碼是一個ubuntu開機後會自動執行的指令碼,我們可以在該指令碼內新增命令列指令。該指令碼位於/etc/路徑下,需要root許可權才能修改。
該指令碼具體格式如下:

#!/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.

#任務指令碼
#開啟mate終端,並在其中執行指令碼
mate-terminal -x /home/myname/mysetup.sh
#任務指令碼
exit 0
  • 一定要將命令新增在 exit 0之前