如何在重启或启动时执行命令或脚本 | Linux 中国
https://linux.cn/article-12279-1.html
作者:Magesh Maruthamuthu
译者:geekpi
有时你需要在启动时添加自定义脚本、命令或服务,该怎么做?你可以使用以下三种方法来做到。
在本文中,我们将通过示例向你展示如何使用这些方法。
方法 1:如何使用 /etc/rc.d/rc.local 文件在重启或启动时运行脚本或命令
传统上,
/etc/rc.local
文件是在切换到多用户运行级别的过程结束时,在所有正常的计算机服务启动之后执行的。此方法也适用于 systemd 系统。
你需要将你的脚本位置添加到
/etc/rc.d/rc.local
文件中以在启动时运行。确保该文件有运行权限:
#chmod+x /etc/rc.d/rc.local
作为演示,我们将创建一个简单的示例脚本。你可以根据需要创建任何脚本。
#vi/opt/scripts/run-script-on-boot.sh
#!/bin/bash
date>/root/on-boot-output.txt
hostname>/root/on-boot-output.txt
脚本完成后,设置可执行权限:
#chmod+x /opt/scripts/run-script-on-boot.sh
最后,将该脚本添加到文件底部:
#vi/etc/rc.d/rc.local
/opt/scripts/run-script-on-boot.sh
重启系统进行检查:
#reboot
方法 2:如何使用 crontab 在重启或启动时执行命令或脚本
此示例在系统重启时运行
/opt/scripts/run-script-on-boot.sh
文件。我们将使用与上面相同的脚本。为此,只需在 crontab 文件中添加以下条目:
# crontab -e
@reboot/opt/scripts/run-script-on-boot.sh
重启系统进行检查:
#reboot
方法 3:如何使用 systemd 服务单元在重启或启动时运行命令或脚本
此方法仅适用于 systemd 系统。该方法非常简单。
我们将使用上面相同的脚本进行演示。
为此,你需要创建一个 systemd 启动脚本并将其放在
/etc/systemd/system/
目录中。这是我们的示例 systemd 启动单元脚本:
#vi sample-on-boot-script.service
[Unit]
Description=Run a CustomScript at Startup
After=default.target
[Service]
ExecStart=/opt/scripts/run-script-on-boot.sh
[Install]
WantedBy=default.target
将单元脚本放置在 systemd 所在位置后,运行以下命令更新 systemd 配置文件并启用服务:
#systemctl daemon-reload
#systemctl enable sample-on-boot-script.service
重启系统进行检查:
#reboot
额外提示
如果你想在后台运行脚本,你需要在最后加上
&
符号/Path/To/My_Script&
如果你想以不同用户运行命令,使用以下格式:
su- $USER -c /Path/To/My_Script
关键词
脚本
文件
系统
方法
中国
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。