linux - 基于 Bash 的热重载实现

标签 linux bash unit-testing automated-tests git-bash

tl;博士版本 问题:如何制作一个 bash 脚本/命令来监听文件的更改,然后输出特定 Bash 命令的结果?

长版 真实场景:我正在重构一个 Perl 模块 (my_module.pm),并且有一个与该模块关联的测试文件 (my_module.t)。我想将控制台放在一个屏幕上,每当我保存 pm 文件(使用另一个屏幕上的编辑器)时,控制台都会运行 prove -v my_module.t

背景:我拥有当前目录的所有权限,如果需要我可以提升到sudo。我不介意实现是否类似于 setInterval 因为它仅用于开发目的。只要我有办法 clearInterval 并且当文件未更改时脚本不会产生永无休止的输出,那就很好了:)

示例场景: 假设 bash 脚本名为 hot,并且只要给定的文件发生更改,它就会运行 ls -l source.txt。 因此,当我运行 hot source.txt 时,脚本可能会也可能不会运行 ls .... 一次。然后,当我修改 source.txt 时,运行 hot 的控制台将再次运行 ls,我应该看到新的文件大小(以及source.txt 的其他信息)。 如果我运行 hot Something.txt,当 source.txt 被修改时,它不应该运行ls。即使 source.txt 未修改,每当我修改 something.txt 时,脚本也应该触发 ls

我想这可以通过 while 循环实现,但我很难跟踪文件更改(最好以一个间隔来跟踪,以减少资源占用)。任何帮助将不胜感激!

最佳答案

使用inotifywait监视文件的更改事件并对其修改运行测试。

inotifywait -q -m -e close_write my_module.pm |
while read -r filename event; do
  prove -v my_module.t
done

标志的用法如下。您的情况下的事件 -e 标志是 close_write ,这意味着文件在最近打开写入后已关闭。

-q, --quiet

If specified once, the program will be less verbose. Specifically, it will not state when 
it has completed establishing all inotify watches. If specified twice, the 
program will output nothing at all, except in the case of fatal errors.

-m, --monitor

Instead of exiting after receiving a single event, execute indefinitely. The default 
behaviour is to exit after the first event occurs.

-e <event>, --event <event>

Listen for specific event(s) only.

close_write

A watched file or a file within a watched directory was closed, after being opened in 
writeable mode. This does not necessarily imply the file was written to.

关于linux - 基于 Bash 的热重载实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42049983/

相关文章:

java - 为具有两个 When 语句的测试获取 WrongTYpeOfReturnValue

c# - 我应该在 n 层应用程序中测试哪一层

java - 从源代码检测对 Java API 方法的调用

linux - 域名疑难解答

bash - 递归复制文件夹,排除部分文件夹

linux - 使用终端删除文件中的某些文本

bash - 将输入传递给 bash 脚本中的多个命令

css - Windows 和 Linux 中 css 定位的区别

linux - makefile 错误 *** 缺少分隔符。停止

c - 以亚微秒精度测量 Linux 内核空间中的时间