在 Ubuntu 里“触发脚本”有很多种含义,常见做法也不同。下面按最常见的几种触发方式给你一个清晰对照,你可以看看哪一种符合你的场景。
bash test.sh
# 或
./test.sh
前提:
chmod +x test.sh
✅ 适合:调试脚本是否正常执行
crontab -e
* * * * * /home/user/test.sh >> /home/user/test.log 2>&1
tail -f /home/user/test.log
✅ 适合:定时任务、自动化脚本
@reboot /home/user/test.sh
sudo nano /etc/systemd/system/test.service
内容:
[Unit]
Description=Test Script
[Service]
ExecStart=/home/user/test.sh
Restart=no
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable test.service
sudo systemctl start test.service
✅ 适合:服务器、后台服务
sudo apt install inotify-tools
inotifywait -m /home/user/watchdir -e modify |
while read path action file; do
/home/user/test.sh
done
✅ 适合:监控目录、自动处理新文件
sudo apt install socat
socat TCP-LISTEN:12345,fork EXEC:/home/user/test.sh
✅ 适合:简单服务触发
[Path]
PathModified=/home/user/watchfile
[Install]
WantedBy=multi-user.target
sudo systemctl enable test.path
sudo systemctl start test.path
✅ 适合:文件变化时自动执行
#!/bin/bash
echo "$(date) script triggered" >> /tmp/test.log
bash test.sh
cat /tmp/test.log
❌ 脚本没执行?
chmod +xenable你可以直接说:
我可以帮你写完整可运行的示例。