如何在ubuntu系統建立開機時執行指令/Autorun command on reboot (Ubuntu 16.04)

Eluspac
Feb 11, 2020

--

crontab除了是一個用作定時執行的工具外,其實它還可以在系統啟動時執行一些指令。以下會利用crontab,講解如何令系統啟用時自動執行一些指令。
*以下教程為個人的成功經驗分享,未必是最佳方法。

主要工具: crontab

目標: 在系統啟動時執行指令: echo “hello world”

流程構思:

  1. 建立一個folder,並在裡面建立一個.sh的 shell script檔案
    (例: /home/ubuntu/sh/test.sh)
  2. 以vim或nano去輸入script,基本框架如下:
#!/bin/bash echo "hello world" exit 0

3. 輸入crontab -e

4. 舉例剛才.sh檔是在/home/ubuntu/sh/test.sh
在crontab中添加一行
@reboot sleep 5; /home/ubuntu/sh/test.sh

5. 這裡要注意的是,因為某些程序,需要在開機後幾秒後才會啟動,所以在前面加了sleep 5秒作緩衝,保險一點。

6. 完成後便可以重啟試試。

在系統重啟時載入screen並在裡面執行指令

目標: 在系統啟動時先打開Screen,並在裡面執行指令: echo “hello world”

做法上也是跟上面大同小異,在crontab中輸入

@reboot sleep 5; /usr/bin/screen -dmS SCREEN_NAME_HERE bash -c "/bin/bash /home/ubuntu/sh/test.sh; exec bash"

其中的SCREEN_NAME_HERE 和 /home/ubuntu/sh/test.sh 請自行修改。

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Eluspac
Eluspac

No responses yet

Write a response