在Debian系统中,要使用nohup命令自动运行脚本,你可以将命令添加到系统的启动脚本中。以下是一些常见的方法:
/etc/rc.local编辑/etc/rc.local文件:
打开终端并输入以下命令来编辑rc.local文件:
sudo nano /etc/rc.local
添加启动命令:
在exit 0之前添加你的nohup命令。例如,如果你想运行一个名为my_script.sh的脚本,可以这样写:
nohup /path/to/my_script.sh &
确保脚本具有可执行权限:
chmod +x /path/to/my_script.sh
保存并退出:
按Ctrl+X,然后按Y确认保存,最后按Enter退出。
重启系统: 重启系统以验证脚本是否自动运行:
sudo reboot
systemd服务创建一个新的服务文件:
创建一个新的服务文件,例如/etc/systemd/system/my_script.service:
sudo nano /etc/systemd/system/my_script.service
添加服务配置: 在文件中添加以下内容:
[Unit]
Description=My Script Service
After=network.target
[Service]
ExecStart=/usr/bin/nohup /path/to/my_script.sh &
Restart=always
User=your_username
[Install]
WantedBy=multi-user.target
重新加载systemd配置:
保存并退出编辑器后,重新加载systemd配置:
sudo systemctl daemon-reload
启用服务: 启用服务以便在系统启动时自动运行:
sudo systemctl enable my_script.service
启动服务: 立即启动服务:
sudo systemctl start my_script.service
检查服务状态: 检查服务是否正在运行:
sudo systemctl status my_script.service
cron的@reboot编辑用户的crontab文件:
打开终端并输入以下命令来编辑当前用户的crontab文件:
crontab -e
添加启动任务: 在文件末尾添加以下行:
@reboot nohup /path/to/my_script.sh &
保存并退出:
按Ctrl+X,然后按Y确认保存,最后按Enter退出。
重启系统: 重启系统以验证脚本是否自动运行:
sudo reboot
选择适合你需求的方法来设置nohup自动运行脚本。通常,使用systemd服务是最推荐的方法,因为它提供了更多的控制和灵活性。