在 ubuntu 18.04 启动时以 root 身份运行 Bash 脚本

Suj*_*nth 3 bash ubuntu-18.04

我想在启动时以 root 身份运行 bash 脚本。首先我开始使用 RC.Local 和 Crontab 但没有任何效果。

Bub*_*han 7

按照下面的模板创建服务文件并将文件添加到该位置 /etc/systemd/system/

模板为

[Unit]
Description = ~Name of the service~

[Service]
WorkingDirectory= ~directory of working file~
ExecStart= ~directory~/filename.sh

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

使用名称启动服务文件

systemctl start servicefile.service
Run Code Online (Sandbox Code Playgroud)

在启动时启用

systemctl enable servicefile.service
Run Code Online (Sandbox Code Playgroud)

检查状态

systemctl status servicefile.service
Run Code Online (Sandbox Code Playgroud)

停止

systemctl stop servicefile.service
Run Code Online (Sandbox Code Playgroud)


Bay*_*you 6

在 /etc/systemd/system/ 中创建一个 systemd 单元文件并使用它来执行脚本。(IE hello-world.service)。

\n
[Unit]\nDescription=Hello world\nAfter=sysinit.target\nStartLimitIntervalSec=0\n\n[Service]\nType=simple\nRestart=no\nRemainAfterExit=yes\nUser=root\nExecStart=/bin/echo hello world\nExecStop=/bin/echo goodby world\n\n[Install]\nWantedBy=multi-user.target\n
Run Code Online (Sandbox Code Playgroud)\n

systemctl现在您可以像使用其他服务一样使用它。

\n
$ systemctl enable hello-world\n$ systemctl start hello-world\n$ systemctl stop hello-world\n$ systemctl status hello-world\n\xe2\x97\x8f hello-world.service - Hello world\n   Loaded: loaded (/etc/systemd/system/hello-world.service; enabled; vendor preset: enabled)\n   Active: inactive (dead) since Wed 2019-10-09 13:54:58 CEST; 1min 47s ago\n  Process: 11864 ExecStop=/bin/echo goodby world (code=exited, status=0/SUCCESS)\n Main PID: 11842 (code=exited, status=0/SUCCESS)\n\nOct 09 13:54:38 lnxclnt1705 systemd[1]: Started Hello world.\nOct 09 13:54:38 lnxclnt1705 echo[11842]: hello world\nOct 09 13:54:57 lnxclnt1705 systemd[1]: Stopping Hello world...\nOct 09 13:54:57 lnxclnt1705 echo[11864]: goodby world\nOct 09 13:54:58 lnxclnt1705 systemd[1]: Stopped Hello world.\n
Run Code Online (Sandbox Code Playgroud)\n

确保在单元文件中使用脚本的完整路径(即/bin/echo)。查看有关以下项中使用的密钥的文档hello-world.service

\n\n