当 linux 系统目录中有新文件创建时执行命令,可以通过组合使用工具和脚本实现监控。一种常见的方法是使用 inotify-tools,这是一个允许您监视文件系统事件的实用程序,与 shell 脚本一起使用。
step 1: 安装 inotify-tools
首先,你需要安装 inotify-tools,通常可以使用包管理器安装它。
sudo apt update sudo apt install inotify-tools
step 2: 创建 shell script
接下来,创建一个 shell 脚本,该脚本使用 inotifywait 来监视目录中是否有新文件,然后在检测到新文件时调用 api,下面是这个脚本的简单示例:
#!/bin/bash # directory to monitor monitor_dir="/path/to/your/directory" # your custom command # custom_command="curl -x post -d @newfile http://your.api.endpoint" # monitor for new files and call the api inotifywait -m -e create --format '%w%f' "$monitor_dir" | while read newfile do echo "new file detected: $newfile" # uncomment to execute custom command #eval $custom_command done
在此脚本中,将 “/path/to/your/directory” 替换为你想监控的目录,将“http://your.api.endpoint”替换为你的上传 api 地址,您也可以修改 custom_command 包括其它数据或参数选项。
step 3: 执行脚本
修改文件权限,让其可以执行
chmod +x monitor.sh
执行脚本
bash monitor.sh
step 4: 后台执行脚本
如果您希望这个脚本在后台连续运行,您可以使用 nohup 或 tmux 会话中运行它。
for example:
nohup ./monitor.sh &
step 5: 以 systemd 服务方式运行脚本
确保您的脚本已正确编写和测试。将其放在合适的目录,例如: /usr/local/bin/
sudo mv monitor.sh /usr/local/bin/
确保它是可执行的
sudo chmod +x /usr/local/bin/monitor.sh
创建一个新的 systemd 服务文件
sudo nano /etc/systemd/system/monitor.service
将以下内容添加到文件中
[unit] description=file monitor service [service] execstart=/usr/local/bin/monitor.sh restart=always user=nobody group=nogroup [install] wantedby=multi-user.target
保存并关闭该文件,重新加载 systemd 管理器配置
sudo systemctl daemon-reload
设置开机启动
sudo systemctl enable monitor.service
启动服务
sudo systemctl start monitor.service
检查服务状态
sudo systemctl status monitor.service
补充说明
- 这个脚本是一个基本的例子。根据具体需求,您可能需要对其进行修改。
- 如果需要更复杂的监视或处理,请考虑使用更健壮的解决方案或编程语言。
- 确保您的脚本是自包含的,不需要交互式输入。systemd 服务不是为交互使用而设计的。
- 如果您的脚本写入日志,请确保它写入一个它有权访问的位置。
到此这篇关于linux使用inotify-tools监控目录变化的流程步骤的文章就介绍到这了,更多相关linux inotify-tools监控目录变化内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论