what is the best way to start a script in boot time on linux

独自空忆成欢 提交于 2020-08-24 03:25:21

问题


I want to start a script I have on when the system start and looking for the best way, my way is:

  • vi /etc/systemd/system/myscript.service

    [Service]
    Type=simple
    ExecStart=/usr/bin/myscript
    CPUSchedulingPolicy=rr
    CPUSchedulingPrioty=27
    [Install]
    WantedBy=multi-user.target graphical.target
    
  • systemctl daemon-reload; systemctl enable myscript; systemctl start rmyscript

it's working good but just wondered if there another and better way.


回答1:


There are a couple of ways to achieve this, but you will need root privileges for any the following. To get root, open a terminal and run the command:

sudo su

and the command prompt will change to '#' indicating that the terminal session has root privileges.

Alternative #1. Add an initscript

Create a new script in /etc/init.d/myscript:

vi /etc/init.d/myscript

(Obviously it doesn't have to be called "myscript".) In this script, do whatever you want to do. Perhaps just run the script you mentioned:

#!/bin/sh
/path/to/my/script.sh

Make it executable:

chmod ugo+x /etc/init.d/myscript

Configure the init system to run this script at startup:

update-rc.d myscript defaults

Alternative #2. Add commands to /etc/rc.local

vi /etc/rc.local

with content like the following:

# This script is executed at the end of each multiuser runlevel
/path/to/my/script.sh || exit 1   # Added by me
exit 0

Alternative #3. Add an Upstart job

Create /etc/init/myjob.conf:

vi /etc/init/myjob.conf

with the following content:

description "my job"
start on startup
task
exec /path/to/my/script.sh

BTW:

You don't need to be root if you can edit your crontab (crontab -e) and create an entry like this:

@reboot /path/to/script.sh

This way, you can run it as a regular user. @reboot just means it's run when the computer starts up (not necessarily just when it's rebooted).



来源:https://stackoverflow.com/questions/40861280/what-is-the-best-way-to-start-a-script-in-boot-time-on-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!